6

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.

dhS
  • 3,739
  • 5
  • 26
  • 55
Bharti Rawat
  • 1,949
  • 21
  • 32
  • 5
    From the point of view of `System.out.println` there is no apparent difference. But certain APIs may require an array rather than a String. – Tim Biegeleisen Nov 22 '16 at 07:37
  • 1
    maybe you want all the unique characters in a `String`, maybe you want to reverse it and though loop over each `char`. All in all i don´t really get the question as there are more than enough examples where you´d need it. – SomeJavaGuy Nov 22 '16 at 07:38
  • @KevinEsche i am somewhat satisfied from your answer. Actually i just only need some examples why i need to use this method? Where can i use this method? I think it is clearly written in my question. – Bharti Rawat Nov 22 '16 at 07:41
  • 1
    It really depends on what you are trying to do. Maybe you want to manipulate the chars, remove some, add some more, stream them, there really are infinite reasons why you may want a char array. When using System.out.println you are really just calling toString on the char array. – LanceP Nov 22 '16 at 07:45
  • 2
    Possible duplicate of [Why is char\[\] preferred over String for passwords in Java?](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java) – cheseaux Nov 22 '16 at 07:48
  • Because in Java, String is immutable and are cached in memory. When dealing with cryptography, there are passwords and you don't ever want passwords to be cached in memory. That's why many cryptographic APIs take a char[] or byte[] for passwords. Some bad programmers don't realize that and use String to store password, and use .toCharArray() when calling those APIs. (http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java) – KC Wong Nov 22 '16 at 07:50
  • 1
    are you looking for examples for chararray like you said in comments `if you add more example for another case` or you want to understand the relation of `chararray` with `hashcode` – Pavneet_Singh Nov 22 '16 at 07:53
  • @PavneetSingh yes exactly i also want it. Thanku for comment. – Bharti Rawat Nov 22 '16 at 08:00

3 Answers3

5

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

Community
  • 1
  • 1
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
1

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.

RichardK
  • 3,228
  • 5
  • 32
  • 52
0

There is a difference between String and charArray.In both of them data is stored in same way it doesnt mean both are same.String is immutable while charArray is not.String is implemented with a char array and each time you try to modify it it gives you a new String object.String behave as Constant due to its immutable properties while Char Araay not.

The use of both depend upon your need and requirement.

Zia
  • 1,001
  • 1
  • 13
  • 25