Strings in Java

Site Admin · 11 Sep 2026 · 12 views

Strings Are Objects

In Java, a String is not a primitive; it is a class that stores a sequence of characters. The class is immutable, meaning once a String object is created its characters cannot be changed.

Common Operations

String city = "Hyderabad";
System.out.println(city.length());        // 9
System.out.println(city.charAt(0));       // H
System.out.println(city.toUpperCase());   // HYDERABAD
System.out.println(city.substring(0, 4)); // Hyde
System.out.println(city.indexOf("bad"));    // 4
System.out.println(city.contains("Hyd"));  // true
System.out.println(city.equals("hyderabad")); // false (case sensitive)

String Pool

Because strings are used so often, the JVM keeps a pool of literal strings and reuses them. Two literals with the same text point to the same pooled object.

String a = "hello";
String b = "hello";
System.out.println(a == b);        // true: same pooled object
System.out.println(a.equals(b));   // true: same characters

String c = new String("hello");   // a brand-new object
System.out.println(a == c);        // false
System.out.println(a.equals(c));   // true - always compare content with equals

String vs StringBuilder vs StringBuffer

// Concatenating in a loop creates many intermediate strings - slow
String s = "";
for (int i = 0; i < 5; i++) s += i;

// StringBuilder is mutable and fast; use it when building strings
StringBuilder sb = new StringBuilder();
sb.append("Java").append(" " ).append("is fun");
System.out.println(sb.toString()); // Java is fun

StringBuilder is not thread safe but faster. StringBuffer is thread safe and slower; most single-threaded code should use StringBuilder.

Escaping Characters

String quote = "She said, \"Hello!\"";
String path = "C:\\Users\\Sam";
String tab = "Column1\tColumn2";

String pool and immutability

String object creation

String memory layout

String after intern

StringBuffer object

String output

Key Points

  • Strings are immutable objects; their characters cannot change.
  • Compare content with equals, never ==.
  • Use StringBuilder for heavy string building.
Share this post:

Comments (0)

Please login or register to comment.