String in Java

Short Answer:
String in Java is an immutable sequence of characters stored in the String pool.

String is a final class in java.lang package. It is widely used in Java applications.


1️⃣ Why String is Immutable?

Short: For security, caching, and thread safety.

  • Prevents modification after creation.
  • Used in String pool.
  • Safe for multithreading.
  • Used in HashMap keys.

2️⃣ String Creation

Method 1: String Literal (Stored in Pool)

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

Both reference same object from String Pool.

Method 2: Using new Keyword

String s3 = new String("Java");

Creates object in heap memory.


3️⃣ String Pool Explained

Short: Special memory area inside heap for string literals.

  • Avoids duplicate objects.
  • Improves memory efficiency.
  • intern() method forces string into pool.

4️⃣ String vs StringBuilder vs StringBuffer

Feature String StringBuilder StringBuffer
Mutable No Yes Yes
Thread Safe Yes No Yes
Performance Slow Fast Medium

5️⃣ Important String Methods

  • equals()
  • length()
  • substring()
  • contains()
  • replace()
  • split()
  • trim()
  • toUpperCase()

Frequently Asked Interview Questions (With Answers)

1️⃣ Difference between == and equals() in String?

Short: == compares reference; equals() compares content.

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b);      // false
System.out.println(a.equals(b)); // true

2️⃣ What is intern() method?

Short: Moves string to String Pool.

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

3️⃣ Why String is final class?

Answer: To prevent inheritance and ensure immutability.


4️⃣ What happens when we concatenate strings?

Short: New object created.

String s = "Java";
s = s + " Spring";

Creates new object; old one remains unchanged.


5️⃣ Why String is used as HashMap key?

Answer: Because it is immutable and hashCode remains constant.


6️⃣ Difference between StringBuilder and StringBuffer?

Answer: StringBuffer is synchronized; StringBuilder is not.


7️⃣ How String stored internally?

Answer: Stored as char array (before Java 9) and byte array (Java 9+).


8️⃣ What is String constant pool?

Answer: Special heap memory area for string literals.


9️⃣ Is String thread-safe?

Answer: Yes, because it is immutable.


🔟 How to compare two strings ignoring case?

s1.equalsIgnoreCase(s2);

0 comments

Leave a comment