Skip to main content

The String Class

In Java, a String is an object that represents a sequence of characters. The java.lang.String class is used to create and manipulate strings.

Strings in Java are heavily optimized and behave slightly differently than typical objects due to two core concepts: Immutability and the String Constant Pool.


1. String Immutability

In Java, String objects are immutable. This means that once a String object is created, its data or state cannot be changed.

Whenever you perform an operation that seems to modify a String (like concatenation or substring), a completely new String object is created in memory, and the old object is left untouched.

public class LabString1 {

public static void main(String args[]) {
String s = "Hello";

// The concat() method appends the string at the end
s.concat(" World");

// Will print "Hello" because strings are immutable
System.out.println(s);

// To see the change, you must explicitly assign the new object to a reference
s = s.concat(" World");
System.out.println(s); // Prints "Hello World"
}
}

[!NOTE] Why are Strings immutable? It makes them thread-safe, enhances security (e.g., database URLs can't be altered), and allows Java to aggressively optimize memory via the String Constant Pool.


2. The String Constant Pool (SCP)

The String Constant Pool is a special memory area inside the Java Heap memory. When you create a String using a string literal, the JVM checks the SCP first.

  • If the string already exists in the pool, a reference to the pooled instance is returned.
  • If the string doesn't exist, a new String instance is created and placed in the pool.

This caching mechanism saves a tremendous amount of memory.

String Literal vs new Keyword

There are two ways to create a String:

  1. By String Literal:

    String s1 = "Welcome";

    String s2 = "Welcome";
    // s1 and s2 point to the SAME object in the String Constant Pool.
  2. By new Keyword:

    String s3 = new String("Welcome");
    // This forces the JVM to create a NEW object in normal Heap Memory (outside the SCP).
    // s1 and s3 point to DIFFERENT objects, even though their contents are the same.

3. Important String Methods

The String class provides dozens of built-in methods. Here are some of the most frequently used ones:

MethodDescriptionExample
length()Returns the number of characters."java".length()4
charAt(int index)Returns the character at the specified index."java".charAt(2)'v'
substring(int beginIndex)Returns a substring starting from the index."javatpoint".substring(4)"point"
contains(CharSequence s)Returns true if it contains the sequence."java".contains("av")true
equals(Object anObject)Compares contents for equality (case-sensitive)."java".equals("JAVA")false
equalsIgnoreCase(String s)Compares contents ignoring case."java".equalsIgnoreCase("JAVA")true
split(String regex)Splits the string into an array based on regex."a,b,c".split(",")["a", "b", "c"]
trim()Removes leading and trailing whitespace." java ".trim()"java"
replace(oldChar, newChar)Replaces all occurrences of a character."java".replace('a', 'e')"jeve"

Example: Working with String Methods

public class LabString2 {

public static void main(String args[]) {
String text = " Learn Java Programming ";

System.out.println("Original: '" + text + "'");
System.out.println("Trimmed: '" + text.trim() + "'");
System.out.println("Length: " + text.length());
System.out.println("Uppercase: " + text.toUpperCase());

String cleanText = text.trim();
System.out.println("Substring: " + cleanText.substring(6, 10)); // Extract "Java"

// Splitting a sentence into words
String[] words = cleanText.split(" ");
System.out.println("First Word: " + words[0]);
}
}