Nearby lessons

109 of 125

Java - Strings

📌 What You Will Learn
  • Why String objects are immutable
  • String vs StringBuffer vs StringBuilder
  • The most important methods of String
  • == vs equals() — the classic interview question
  • How to split, join and manipulate text

Strings is a core concept of the Java language. This lesson explains What is a String?, Strings Are Immutable and String Pool — Two Statements, One Big Difference with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is a String?

A String in Java is a sequence of characters. But it is a special thing: String is not a primitive type, it is a class that Java provides for us. Every time you write double quotes, Java creates a String object.

Strings are stored in a special area of memory called the String Constant Pool. When you write a string literal, Java first checks the pool — if the same value already exists, it reuses that object instead of creating a new one.

Example01
JCode Cell
1String name = "Rahul"; // String object created
2String city = new String("Delhi"); // another way (not recommended)

Strings Are Immutable

Immutable means: once a String object is created, its content can never be changed. If you try to change it, Java creates a new String object and leaves the old one as it is.

In simple words: An immutable String can never be changed after it is created. Every method like concat() or toUpperCase() returns a brand-new String, so the original stays exactly as it was until you reassign the variable.

Why make Strings immutable? Main reasons: security (strings like passwords and class names must not be changed by accident), thread safety (many threads can safely share one immutable object), and caching (reusing the same value from the pool saves memory).

Example02
JCode Cell
1String s = "Java";
2s.concat(" Rocks"); // result is a NEW String, s still "Java"
3System.out.println(s); // Java
4 
5s = s.concat(" Rocks"); // now s points to the new String
6System.out.println(s); // Java Rocks
Output
Java Java Rocks

String Pool — Two Statements, One Big Difference

The classic material asks: what is the difference between these two statements?

  • Statement 1 creates (or reuses) the String in the String Constant Pool (inside the method area).
  • Statement 2 creates a new object in the heap (plus, the literal "abc" may also go to the pool).

Important note about memory: objects in the String Constant Pool are not eligible for garbage collection; objects in the heap are eligible. And remember the golden rule — s1 == s2 is false (different objects), s1.equals(s2) is true (same content).

In simple words: `new String("abc")` always creates a fresh heap object, while the literal `"abc"` reuses the pool object. That is why two statements can hold the same text yet fail == — compare content with .equals().
Example03
JCode Cell
1String s1 = "abc"; // statement 1
2String s2 = new String("abc"); // statement 2

== vs equals() — The Classic Question

This is the most asked String question in interviews. Understand it perfectly:

  • == compares references — are they the same object in memory?
  • .equals() compares content — is the text inside the same?
In simple words: `==` compares references and `.equals()` compares content. Two strings with the same text can still be different objects in memory, so == may say false — always use .equals() to compare String values.
Trainer's Note: Because of the String pool, "Java" == "Java" is true. But if even one String is created with new, the references differ. So the golden rule stays: compare Strings with `.equals()`, never with ==.
Example04
JCode Cell
1String a = "Java";
2String b = "Java";
3String c = new String("Java");
4 
5System.out.println(a == b); // true (both point to same pool object)
6System.out.println(a == c); // false (c is a different object)
7System.out.println(a.equals(c)); // true (same content)
Output
true false true

toString() — Print an Object Nicely

When you print an object with System.out.println(obj), Java calls its toString() method. The default toString() prints a code like Student@4aa298b7 (class name + memory code). We usually override it to print useful information.

Example05
JCode Cell
1class Student {
2 int rollNo;
3 String name;
4 Student(int r, String n) { rollNo = r; name = n; }
5 
6 public String toString() {
7 return "Student[rollNo=" + rollNo + ", name=" + name + "]";
8 }
9}
10 
11class Test {
12 public static void main(String[] args) {
13 Student s = new Student(101, "Rahul");
14 System.out.println(s); // calls toString() automatically
15 }
16}
Output
Student[rollNo=101, name=Rahul]

String Constructors

A String object can be created in many ways. The important constructors:

Example06
JCode Cell
1String s1 = new String(); // empty string ""
2String s2 = new String("abc"); // from a String
3String s3 = new String(char[] ch); // from a char array
4String s4 = new String(byte[] b); // from a byte array
5String s5 = "abc"; // simple literal (pool)
📝 Key Takeaways
  • String is a class, not a primitive; it is immutable.
  • Immutability gives security, thread safety and pool caching.
  • Use StringBuilder (fastest, not thread-safe) or StringBuffer (thread-safe) when text changes often.
  • == compares references; .equals() compares content. Always use .equals() for Strings.
  • Override toString() to print objects meaningfully.
  • Text blocks (Java 15+) make multi-line strings clean.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2