Junior — Middle
How is memory organized and what is the data structure inside a string in a programming language?
sobes.tech AI
Answer from AI
In Java, strings are represented by objects of the String class, which are immutable. Inside the String object, there is a character array (char[]), where the string's characters are stored.
The structure is roughly as follows:
- Field char[] value — an array of characters that holds the string content.
- Field int hash — a cached hash code value for optimization.
Since strings are immutable, any modification results in the creation of a new object with a new character array.
Example:
String s = "hello";
// Inside s, there is a reference to the array ['h','e','l','l','o']
In newer versions of Java (starting from Java 9), an array of bytes (byte[]) with encoding information (LATIN1 or UTF16) is used for memory optimization.