How are strings stored in memory in Java?
sobes.tech AI
Answer from AI
In Java, a string (String) is an immutable object. Its value is represented by a sequence of characters.
Before Java 9, String stored characters in a char[] array. Each character occupied 2 bytes (UTF-16).
// Before Java 9
public final class String implements Serializable, Comparable<String>, CharSequence {
private final char value[]; // String characters
private final int offset; // Starting offset
private final int count; // Number of characters (length)
// ... other fields and methods
}
Since Java 9, to save memory, String can use either a byte[] array (for ASCII/Latin-1 characters) or a char[] array (for UTF-16 characters). The encoding is determined by the coder flag.
// From Java 9
public final class String implements Serializable, Comparable<String>, CharSequence {
private final byte[] value; // String characters (byte[] or char[] essentially, depending on coder)
private final byte coder; // Encoding: 0 for Latin-1, 1 for UTF-16
// ... other fields and methods
}
String literals (allowed characters) and strings created with the new String(...) operator are stored on the heap.
String literals are also placed in the "String Pool" located in the PermGen space (before Java 8) or in MetaSpace (from Java 8). If a string with the same value already exists in the pool, a reference to the existing object is used.
String s1 = "hello"; // Creates "hello" in String Pool (if not already there), s1 references it
String s2 = "hello"; // s2 references the same "hello" object in String Pool
String s3 = new String("hello"); // Creates a new "hello" object on the heap, s3 references it. "hello" may be in String Pool
Since strings are immutable, changing the value of a string (e.g., concatenation) results in creating a new String object in memory.