Strings in Java

Naveen AnamaneniUpdated · 5 min read

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

Create.java▶ Try it
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));
    }
}
Output
Navika, Srihitha, Advitha, 2026
6 letters, first is N

How it works

  1. "Navika" is a string literal: text written directly in the code. This is the normal way to create a string.
  2. new String("Srihitha") forces a brand-new object. It works, but you'll rarely need it (the next lesson explains why).
  3. A char[] can be turned into a string, and String.valueOf turns numbers and other values into text.
  4. length() counts the characters, and charAt(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.

Literals share one pooled object; new String makes another
Pool.java▶ Try it
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));
    }
}
Output
true
false
true

How it works

  1. a and b are both the literal "Navika", so they point to the same pooled object. ==, which checks "same object?", says true.
  2. new String(...) always builds a new object outside the pool, so a == c is false.
  3. equals compares the characters, so a.equals(c) is true. 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:

javap -c Pool (trimmed)
         0: ldc           #7                  // String Navika
         3: ldc           #7                  // String Navika

Both 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

  1. Easy: Create your full name as a string, and print its length, its first character and its last character.
  2. Harder: Predict, then check: String x = "Java"; String y = "Ja" + "va"; String z = new String("Java"); What do x == y, x == z and x.equals(z) print?

Quick check: Strings

4 questions
1What is a String in Java?
2String a = "Hi"; String b = "Hi"; What is a == b?
3Which compares the text of two strings?
4Why is sharing pooled strings safe?

Key Takeaways

Was this tutorial helpful?

Lesson 187 of 482