Java String Class: Complete Guide with Examples

In Java, a String is a sequence of characters. Strings are one of the most commonly used objects in Java programming. The String class belongs to java.lang package and provides many built-in methods.

String Creation in Java

Strings can be created in two ways:

1. Using String Literal

String s1 = "Java";

2. Using new Keyword

String s2 = new String("Java");

String literals are stored in the String Constant Pool while objects created using new are stored in heap memory.

String Immutability in Java

Strings in Java are immutable, meaning their values cannot be changed once created.

Example

String s = "Java";
s.concat(" Programming");

System.out.println(s); // Output: Java

The original string is not modified. A new string object is created instead.

String Constant Pool (SCP)

The String Constant Pool is a special memory area where Java stores string literals. If a string already exists in the pool, Java reuses it to save memory.

Example

String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2); // true

Both references point to the same object in the pool.

Important String Methods

Java String class provides many useful methods for string manipulation.

Common Methods

  • length() → returns length
  • toUpperCase()
  • toLowerCase()
  • charAt()
  • equals()
  • equalsIgnoreCase()
  • substring()

Example

String s = "Java";

System.out.println(s.length());
System.out.println(s.toUpperCase());
System.out.println(s.charAt(1));

String Comparison

Strings should be compared using equals(), not ==.

Example

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

StringBuffer in Java

StringBuffer is a mutable class, meaning its value can be changed. It is thread-safe (synchronized).

Example

StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");

System.out.println(sb);

StringBuilder in Java

StringBuilder is similar to StringBuffer but not synchronized, making it faster in single-threaded environments.

Example

StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");

System.out.println(sb);

String Summary

  • String is immutable
  • Stored in String Constant Pool
  • Use equals() for comparison
  • StringBuffer → thread-safe
  • StringBuilder → faster

Java String FAQ

Why String is immutable?

To improve security, performance, and memory optimization.

What is String Pool?

A memory area where string literals are stored and reused.

Difference between StringBuffer and StringBuilder?

StringBuffer is thread-safe, StringBuilder is faster but not thread-safe.