Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of convert a String to charArray?

Tags:

java

I know this the very basic question. But i am very confused in it. Properly i am not getting that why we need to convert a String to CharArray. I know the work of toCharArray() method. Only i want some real time example that why we need this method. In my question i want also understand the relation of charArray with hashcode.

I know charArray representation:

char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

Example

public class Test {

public static void main(String args[]){
    String a = "bharti";
    char[] charArray = a.toCharArray();
    System.out.println(charArray);

} 
}

Output: bharti

For me there is no difference between output and my string bharti in variable 'a'.

Problem creation source :
Actually i want to writing a code to generate a hash password so i was reading some code from google there mostly toCharArray() method is used in it.So i didn't get we why are using this.

like image 417
Bharti Rawat Avatar asked Nov 22 '16 07:11

Bharti Rawat


2 Answers

Converting from String to char[] is useful if you want to do something with the order of the elements, for example sort() them.

String is immutable and not very suited for manipulation.

For example:

    String original = "bharti";
    char[] chars = original.toCharArray();
    Arrays.sort(chars);
    String sorted = new String(chars);
    System.out.println(sorted);

which prints:

abhirt


Also, some methods/classes explicitly require a char[] as input, for example PBEKeySpec

byte[] salt = new byte[16];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = f.generateSecret(spec).getEncoded(…

The rationale is that you can wipe the char[] contents from memory. See more information here: https://stackoverflow.com/a/8881376/461499

like image 58
Rob Audenaerde Avatar answered Sep 30 '22 20:09

Rob Audenaerde


It's useful if you want to check each character inside String, not the whole String, for example:

public boolean hasDigit (String input){
    for (char c: input.toCharArray()){
        if (Character.isDigit(c)){
            return true;
        }
    }
    return false;
}

This method checks if one of characters inside String is a digit.

like image 26
RichardK Avatar answered Sep 30 '22 20:09

RichardK