Back to Study Material Java

Strings in Java

In Java, a String is an object of the java.lang.String class that stores a sequence of characters. Unlike many other languages where strings are simple cha...

Strings in Java

How Java Represents Strings

In Java, a String is an object of the java.lang.String class that stores a sequence of characters. Unlike many other languages where strings are simple character arrays, Java strings are full objects with methods for searching, comparing, transforming, and extracting substrings. One of the most important characteristics of Java strings is that they are immutable: once a String object is created, its contents cannot be changed. Any operation that appears to modify a string actually creates a new String object.

The String Pool Java maintains a special area of memory called the string pool (inside the heap). When you write String s = "hello", Java checks whether "hello" already exists in the pool. If it does, s refers to the same object. If not, Java creates a new object and adds it to the pool. This sharing saves memory when many variables hold the same string value. When you use new String("hello"), Java always creates a fresh object outside the pool.

Common String Methods length() returns the number of characters. charAt(index) returns the character at a given position. substring(start, end) extracts part of the string. indexOf(str) finds the first occurrence of a substring. toLowerCase() and toUpperCase() change case. trim() removes leading and trailing whitespace. equals(other) compares content, while == compares object references—a very common source of bugs.

String Concatenation Internally The + operator compiles to StringBuilder operations at the bytecode level when used inside a loop in modern Java. However, in older code or across multiple statements, repeated concatenation creates many intermediate String objects. For performance-sensitive code that builds strings piece by piece, prefer StringBuilder explicitly.

Code Example: String name = "Java"; System.out.println(name.length()); // 4 System.out.println(name.charAt(0)); // J System.out.println(name.toUpperCase()); // JAVA System.out.println(name.substring(0, 2)); // Ja System.out.println("java".equals(name)); // false

Interview Tip: The single most tested Java string question is the difference between == and equals(). Always use equals() to compare string content. A follow-up question often asks about the string pool and the intern() method, which manually adds a string to the pool and returns the pooled reference.