EMZETT.
Login

Strings

In short: The data type for text in Java — technically an object (not a primitive type), but with special handling that makes using it feel almost like a primitive type.

In more detail: String objects are immutable: every apparent change (e.g. .toUpperCase()) actually creates a new object, the original stays unchanged. Because of the so-called “string pool”, == can, by coincidence, return true for two identically written string literals — but for a reliable content comparison, .equals() should always be used.

In Depth

String a = "Hello";
String b = "Hello";
String c = new String("Hello");
 
System.out.println(a == b);        // true - both literals point to the same pool entry
System.out.println(a == c);        // false - new String() forces its own object
System.out.println(a.equals(c));   // true - content is identical
 
String upper = a.toUpperCase();    // creates a NEW object, "a" itself stays "Hello"
System.out.println(a);             // still "Hello"

Java strings are special for two reasons: first, string literals (written in quotes directly in the code) automatically land in the so-called string pool, a shared memory area — two identically written literals therefore internally point to the same object, which is why == (which compares object identity, not content) appears to reliably return true here. Objects forced with new String(...) deliberately bypass the pool and return false for ==, even though the content is identical — this is exactly why == is an antipattern for strings, and .equals() should always be used.

Second, strings are immutable: every method that apparently “changes” the string (.toUpperCase(), .replace(), .substring(), etc.) actually returns a COMPLETELY NEW string object, the original stays untouched. This automatically makes strings thread-safe (no other thread can change them afterwards) and is what makes the string pool possible in the first place — if strings were mutable, a change via one reference could unexpectedly affect all other places in the program using the same pool object.

See also: String Concatenation, Special Characters, Non-primitive Types