Junior — Middle
How is string data stored in RAM?
sobes.tech AI
Answer from AI
In Java, string data is stored as objects of the class String. In memory, a string is represented as an array of characters (in modern Java versions — a char[] array or a byte[] array with UTF-16 encoding).
Each character takes up 2 bytes (16 bits), as Java uses UTF-16 to represent characters. The String object contains a reference to this array and additional fields, such as the length of the string.
Strings in Java are immutable, so when a string is modified, a new object is created, and the old one remains unchanged.
Example:
String s = "Привет";
// In memory, a String object is created, which contains a reference to an array of characters ['П', 'р', 'и', 'в', 'е', 'т']
Java also uses a string pool — a special area in memory where string literals are stored to save memory and improve performance.