Java: String

Q. Why string is immutable in java?

The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect all another client.

Since string is immutable it can safely share between many threads and avoid any synchronization issues in java.

Q. What is Java String Pool?

String Pool in java is a pool of Strings stored in Java Heap Memory. String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.

When we use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. However using new operator, we force String class to create a new String object in heap space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Java program to illustrate String Pool
*
**/
public class StringPool {

public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");

System.out.println("s1 == s2 :" +(s1==s2)); // true
System.out.println("s1 == s3 :" +(s1==s3)); // false
}
}