Table of Contents
What is a String in Java?
In Java, a String is a sequence of characters (like “Hello, World!”) stored as an object of the java.lang.String
class. Unlike primitive types (int
, char
, etc.), Strings are objects with built-in methods for text manipulation.
Key Facts:
- Strings are immutable (unchangeable after creation – see Java String immutability for details).
- Java stores Strings in a special memory area called the String Pool (more on this below).
How to Create Strings in Java
1. String Literals (Most Common)
String greeting = "Hello"; // Stored in the String Pool
Java automatically checks the String Pool for duplicates. If “Hello” exists, it reuses it.
2. Using the new
Keyword
String greeting = new String("Hello"); // Forces a new object in heap memory
Creates a new object even if “Hello” exists in the String Pool.
The String Pool: Memory Optimization
Java’s String Pool is a special memory region for storing unique String literals. This minimizes memory waste by reusing identical Strings.
Example: Literals vs. new
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2); // true (same memory address in the Pool)
System.out.println(s1 == s3); // false (different memory locations)
Interning Strings
Force a String into the Pool using intern()
:
String s4 = s3.intern(); // Adds s3's value to the Pool if missing
System.out.println(s1 == s4); // true
Why Does This Matter?
- Performance: Reusing Strings saves memory.
- Equality Checks: Use
.equals()
instead of==
for value comparison (Java String Comparison covers this in depth).
Common Mistakes to Avoid
❌ Using ==
for value comparison:
if (new String("test") == "test") { ... } // False!
✅ Always use .equals()
:
if (new String("test").equals("test")) { ... } // True
Key Takeaways
- Prefer String literals (
"text"
) overnew String()
for memory efficiency. - The String Pool reduces redundancy by reusing literals.
- Immutability ensures safe sharing of Strings across your code.
FAQs
Can I modify a String after creating it?
No – use StringBuilder
for mutable operations (see Java String Performance)
How does the String Pool work with garbage collection?
Pooled Strings stay in memory until the JVM exits.