What is the need to convert String to charArray?

I know this is the easiest question. But I am very confused. That's right, I do not get this , why do we need to convert String to CharArray . I know the operation of the toCharArray() method. Only I need a real-time example of why we need this method. In my question, I also want to understand the relation of charArray with hashcode.

I know the charArray view:

 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 and my bharti string in the variable 'a .

Source of the problem :
Actually, I want to write code to generate a hash password, so I read some code from google, the toCharArray () method is mainly used there. Therefore, I did not understand why this is used.

+6
source share
3 answers

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

The string is immutable and not very suitable for manipulation.

For instance:

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

which prints:

abhirt


In addition, some methods / classes explicitly require char[] , 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 erase the contents of char [] from memory. See more information here: fooobar.com/questions/251 / ...

+4
source

Useful if you want to check each character inside a String, and not the entire 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 the characters inside the String is a digit.

0
source

There is a difference between String and charArray. In both cases, the data is stored the same, but this does not mean that they are both the same. String is immutable, but charArray is not. String is implemented with a char array and every time you try to change it, it gives you a new String object. String behaves like a constant due to its immutable properties, and char Araay not.

Using both depends on your needs and requirements.

0
source

Source: https://habr.com/ru/post/1012555/


All Articles