← Back to Home

String Class

The String class in Java represents a sequence of characters and is one of the most important and frequently used classes in Core Java. It is heavily tested in interviews and widely used in real-time applications.

What Is a String in Java?

  • A String is an object that represents a sequence of characters
  • Belongs to the java.lang package
  • Immutable in nature
  • Stored in String Constant Pool (SCP) or Heap
String s = "Java";
          

Why Is String So Important?

  • Used for user input, messages, logs, data exchange
  • Frequently used in APIs and frameworks
  • Optimized for memory using String Constant Pool
  • Core interview topic (immutability, == vs equals())

String Creation Ways (Very Important)

1. Using String Literal (SCP)

String s1 = "Java";
String s2 = "Java";
          
  • Stored in String Constant Pool
  • Same object reused
  • Memory efficient
System.out.println(s1 == s2); // true
          

2. Using new Keyword (Heap)

String s3 = new String("Java");
String s4 = new String("Java");
          
  • Stored in Heap memory
  • Creates new object every time
System.out.println(s3 == s4); // false
          

String Immutability (Interview Favorite)

What Is Immutability?

  • Once a String object is created, it cannot be changed
  • Any modification creates a new object
String s = "Java";
s = s.concat(" World");
          

Result:

  • "Java" remains unchanged
  • New object "Java World" is created

Why Strings Are Immutable?

  • Security (classpath, passwords)
  • Thread safety
  • Performance optimization via SCP
  • Caching and hashcode stability

String Constant Pool (SCP)

  • Special memory area inside heap
  • Stores only unique string literals
  • Improves memory efficiency
String a = "Test";
String b = "Test"; // reused from SCP
          

== vs equals() (Very Important)

Using ==

Compares references (memory address)

String a = "Java";
String b = "Java";
System.out.println(a == b); // true
          

Using equals()

Compares content

String c = new String("Java");
System.out.println(a.equals(c)); // true
          

Commonly Used String Methods

Length

int len = s.length();
          

Concatenation

String s = "Java" + " Programming";
String s2 = s.concat(" Language");
          

Character Access

char ch = s.charAt(1);
          

Comparison

s.equals("Java");
s.equalsIgnoreCase("java");
          

Substring

String sub = s.substring(0, 4);
          

Contains / StartsWith / EndsWith

s.contains("av");
s.startsWith("Ja");
s.endsWith("va");
          

Replace

String r = s.replace("Java", "Core Java");
          

Trim

String t = " Java ".trim();
          

Case Conversion

s.toUpperCase();
s.toLowerCase();
          

String Concatenation Internals

String s = "Java" + "World";
          
  • Compiler optimizes literals
  • At runtime, uses StringBuilder for variables

String vs StringBuilder vs StringBuffer

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread-Safe Yes No Yes
Performance Slow (modifications) Fast Slower than SB
Use Case Read-only Single-threaded Multi-threaded

Common Beginner Mistakes

  • Using == instead of equals()
  • Excessive string concatenation in loops
  • Not understanding immutability
  • Using new String() unnecessarily
  • Ignoring performance impact

Interview-Ready Answers

Short Answer

String is an immutable class in Java used to represent a sequence of characters.

Detailed Answer

In Java, String is an immutable object stored in the String Constant Pool or heap. Any modification creates a new object. This design improves security, memory efficiency, and thread safety. Content comparison is done using equals() rather than ==.

Key Takeaway

The String class is simple on the surface but deep in behavior. Understanding immutability, SCP, memory behavior, and comparison methods is essential for writing efficient Java code and clearing interviews.

String Class Practice Examples

1. Creating a String Using Literal

String s = "Java";
          

Explanation

  • Stored in String Constant Pool (SCP).
  • Memory efficient.
  • Most commonly used approach.

2. Creating a String Using new Keyword

String s = new String("Java");
          

Explanation

  • Creates a new object in heap memory.
  • Not reused from SCP.
  • Rarely recommended unless explicitly needed.

3. Comparing Strings Using ==

String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);
          

Explanation

  • Compares references, not content.
  • Output: true (same SCP reference).

4. Comparing Strings Using .equals()

String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2));
          

Explanation

  • Compares content.
  • Output: true.
  • Always use .equals() for string comparison.

5. Case-Insensitive Comparison

String s1 = "java";
String s2 = "JAVA";
System.out.println(s1.equalsIgnoreCase(s2));
          

Explanation

  • Ignores letter case.
  • Output: true.

6. Finding Length of String

String s = "Automation";
System.out.println(s.length());
          

Explanation

  • Returns number of characters.
  • Output: 10.

7. Access Character Using charAt()

String s = "Java";
System.out.println(s.charAt(1));
          

Explanation

  • Index starts from 0.
  • Output: a.

8. Loop Through String Characters

String s = "JAVA";
for (int i = 0; i < s.length(); i++) {
  System.out.println(s.charAt(i));
}
          

Explanation

  • Iterates character by character.
  • Common interview example.

9. Convert String to Uppercase

String s = "java";
System.out.println(s.toUpperCase());
          

Explanation

  • Creates a new String object.
  • Output: JAVA.

10. Convert String to Lowercase

String s = "JAVA";
System.out.println(s.toLowerCase());
          

Explanation

  • Original string remains unchanged.
  • Output: java.

11. Remove Leading and Trailing Spaces (trim())

String s = "  Java  ";
System.out.println(s.trim());
          

Explanation

  • Removes spaces from start and end only.
  • Output: Java.

12. Check if String Is Empty

String s = "";
System.out.println(s.isEmpty());
          

Explanation

  • Returns true if length is 0.

13. Check if String Is Blank (Java 11+)

String s = "   ";
System.out.println(s.isBlank());
          

Explanation

  • Returns true for whitespace-only strings.
  • Interview favorite.

14. Check if String Contains Substring

String s = "Selenium Java";
System.out.println(s.contains("Java"));
          

Explanation

  • Returns true if substring exists.

15. Replace Characters in String

String s = "Java";
System.out.println(s.replace('a', 'o'));
          

Explanation

  • Output: Jovo.
  • Original string remains unchanged.

16. Replace Substring

String s = "I love Java";
System.out.println(s.replace("Java", "Selenium"));
          

Explanation

  • Replaces entire substring.
  • Output: I love Selenium.

17. Split String into Array

String s = "Java Selenium TestNG";
String[] parts = s.split(" ");
for (String part : parts) {
  System.out.println(part);
}
          

Explanation

  • Splits based on delimiter.
  • Very common in automation.

18. Convert String to Char Array

String s = "Java";
char[] chars = s.toCharArray();
for (char c : chars) {
  System.out.println(c);
}
          

Explanation

  • Useful for character processing problems.

19. Check String Starts With / Ends With

String s = "automation@test.com";
System.out.println(s.startsWith("automation"));
System.out.println(s.endsWith(".com"));
          

Explanation

  • Used heavily in validations.

20. String Immutability Demonstration

String s = "Java";
s.concat(" Selenium");
System.out.println(s);
          

Explanation

  • Output: Java.
  • Strings are immutable.
  • concat() creates a new object.

21. Proper Way to Modify String

String s = "Java";
s = s.concat(" Selenium");
System.out.println(s);
          

Explanation

  • Reassignment required.
  • Output: Java Selenium.

22. Substring Extraction

String s = "Automation";
System.out.println(s.substring(0, 4));
          

Explanation

  • Extracts part of string.
  • Output: Auto.

23. Substring with Single Index

String s = "Automation";
System.out.println(s.substring(5));
          

Explanation

  • Starts from index to end.
  • Output: mation.

24. String Concatenation Using +

String s = "Java" + " " + "Selenium";
System.out.println(s);
          

Explanation

  • Compiler uses StringBuilder internally.
  • Simple and readable.

25. Interview Summary Example (Most Common)

String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
          

Explanation

  • == → reference comparison → false.
  • .equals() → content comparison → true.
  • Very common interview question.