![]() |
VOOZH | about |
Unlike C/C++ Character arrays and Strings are two different things in Java. Both Character Arrays and Strings are a collection of characters but are different in terms of properties.
Differences between Strings and Character Arrays:
| Property | String | Character Array |
|---|---|---|
| Definition | A sequence of characters is represented as a single data type. | A sequential collection of characters of the data type char. |
| Mutability | Immutable - Once created, their values cannot be changed. | Mutable - Individual characters can be modified. |
| Built-in Functions | Provides many built-in functions like substring(), charAt(), length(), etc. | No built-in functions for operations. |
| Concatenation | Strings can be concatenated using the + operator. | Cannot use + for concatenation; must use loops or utility methods. |
| Access Characters | Characters can be accessed using the charAt() method. | Characters can be accessed using array indexing ([]). |
| Memory Storage | Can be stored anywhere in memory, typically managed by the JVM. | Elements are stored contiguously in increasing memory locations. |
| String Constant Pool | Strings are stored in String Constant Pool if they are string literals or interned, otherwise they are stored in the heap. | Stored in the Heap. |
| Security | Not preferred for storing passwords due to immutability and persistence in the String Pool. | Preferred for storing passwords as they can be explicitly cleared after use. |
| Conversion | Can be converted to a Character Array using the toCharArray() method. <br> Example: String s = "GEEKS"; char[] ch = s.toCharArray(); | Can be converted to a String using the String constructor. <br> Example: char[] a = {'G', 'E', 'E', 'K', 'S'}; String A = new String(a); |