Difference between String and Character array in Java

In this post, we will discuss the difference between string and character array in Java.


 

Unlike C/C++, string and character arrays are two different things in Java. Although, String is itself backed by a final character array underneath, there are few important differences between the two which are covered in this post.

 
1. String class has several useful methods to operate on a String instance such as contains(), equals(), length(), trim(), indexOf(), replace(), substring(), etc while a character array doesn’t have any such methods which operates on its values. The character array only offers the length property.

 
2. A String is immutable in Java while a character array is mutable. This means that contents of a String object cannot be changed once it is created. Any operation that results in modification of data will result in a new String.

 
3. The addition (+) operator is overloaded for the String class and it can be used to concatenate two strings. Note that since String is immutable, String concatenation operator will produce a new String.

 
4. All string literals are stored in the String constant pool. They remain in the pool until they became eligible for the garbage collection, while a Character array is stored in heap memory.

 
5. Character array should be preferred over a String for storing passwords in Java. The immutable property of String makes it vulnerable for storing passwords as we can’t get rid of the password after usage until garbage collector collects it. On the other hand, a Character array is mutable and can be cleared immediately after use before the garbage collection kicks in.

 
6. We cannot iterate over characters of a String using an enhanced for-loop. On the other hand, we can iterate over the character array using enhanced for loop (for-each loop) as shown below:

 
7. We can convert a String to a char array using toCharArray method of the String class. To get an Character[], we can use Java 8.

 
In order to convert a char array to String in Java, we can pass it into the String constructor. We can even encapsulate the String constructor call by using valueOf() or copyValueOf() method of the String class.

 
8. To access a specific character in a character array, we pass its index to the [] operator and to access a specific character in a string, we can pass its index to its charAt() method.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of