InterviewSolution
| 1. |
String Pool in Java |
|
Answer» String Pool in Java is a pool or collection of Strings stored in the Java Heap Memory. When initialize a String using double quotes, it first SEARCHES for String with same value in the String pool. If it matches, it just RETURNS the reference otherwise, it generates a new String in the String pool and then it returns its reference. The possibility of the String Pool exists only DUE to the immutability of the String in Java. In CASE of the creation of String using the new operator, the String class is entitled to create a new String in the String Pool. For example, public class Example { public static void main(String[] args) { String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); System.out.println("Do s1 and s2 have the same address? "+ (s1==s2)); System.out.println("Do s1 and s2 have the same address? "+ (s1==s3)); } }The OUTPUT will show that s1 and s2 have the same address due to implementation of String Pool. String s3 though will have a different address due to the use of the new keyword. $javac Example.java $java Example Do s1 and s2 have the same address? true Do s1 and s2 have the same address? false |
|