Strings in Java
Almost every program works with text: names, messages, addresses, passwords, file contents. In Java, a piece of text is a String: an object that holds a sequence of characters, like "Navika" or "Order shipped". Strings are used so much that Java gives them special treatment. You can write them directly in quotes, join them with +, and Java quietly shares identical text to save memory. Understanding that sharing is the key to most string interview questions.
Creating Strings
public class Create {
public static void main(String[] args) {
String a = "Navika";
String b = new String("Srihitha");
char[] letters = {'A', 'd', 'v', 'i', 't', 'h', 'a'};
String c = new String(letters);
String d = String.valueOf(2026);
System.out.println(a + ", " + b + ", " + c + ", " + d);
System.out.println(a.length() + " letters, first is " + a.charAt(0));
}
}Navika, Srihitha, Advitha, 2026
6 letters, first is NHow it works
"Navika"is a string literal: text written directly in the code. This is the normal way to create a string.new String("Srihitha")forces a brand-new object. It works, but you'll rarely need it (the next lesson explains why).- A
char[]can be turned into a string, andString.valueOfturns numbers and other values into text. length()counts the characters, andcharAt(0)reads the first one. Positions start at 0, just like arrays.
The String Pool: Why Identical Text Is Shared
Picture a big program where the word "INR" appears in a thousand places. If each one were a separate object, that's a thousand copies of the same three letters. Instead, Java keeps a special area called the String pool. When it meets a string literal, it checks the pool first: if the same text is already there, it reuses that object instead of making a new one.
public class Pool {
public static void main(String[] args) {
String a = "Navika";
String b = "Navika";
String c = new String("Navika");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
}
}true
false
trueHow it works
aandbare both the literal"Navika", so they point to the same pooled object.==, which checks "same object?", saystrue.new String(...)always builds a new object outside the pool, soa == cisfalse.equalscompares the characters, soa.equals(c)istrue. That's the comparison you almost always want.
Sharing is only safe because strings can never change after they're created (see "Why String Is Immutable in Java"). If one piece of code could edit the shared "INR", every other place using it would suddenly see different text.
Common Mistakes
Comparing with ==. It may work in a small test with literals, then fail with text read from a user or a file.
Forgetting that positions start at 0. The last character of s is s.charAt(s.length() - 1).
Writing new String("text") out of habit. It wastes an object; a literal is enough.
Under the Hood
When you compile String a = "Navika";, the text is stored in the class file's constant pool, and the bytecode loads it with an ldc instruction:
0: ldc #7 // String Navika
3: ldc #7 // String NavikaBoth lines load the same constant, entry #7, which is why a == b. Since Java 7, the pool lives in the ordinary heap, so pooled strings are garbage collected like other objects when nothing uses them.
Since Java 9, strings also use compact strings: text made only of Latin-1 characters (English letters, digits, common symbols) is stored with one byte per character instead of two, roughly halving the memory for most strings. You don't change anything in your code to get this.
Interview Corner
What is the String pool?
The String pool is a special store of unique string objects kept by the JVM. When the code uses a string literal, the JVM returns the pooled object for that text if one exists, instead of creating a new one, so identical literals share a single object. This saves memory, and it's safe because strings are immutable. Since Java 7 the pool is part of the main heap.
Is String a primitive type in Java?
No. String is a class in java.lang, so every string is an object. Java gives it special support: literals in double quotes, the + operator for joining, and the string pool.
Practice
- Easy: Create your full name as a string, and print its length, its first character and its last character.
- Harder: Predict, then check:
String x = "Java"; String y = "Ja" + "va"; String z = new String("Java");What dox == y,x == zandx.equals(z)print?
Key Takeaways
Was this tutorial helpful?