| 1. |
What does the string intern() method do in Java? |
|
Answer» If you apply the intern() method to a few strings, you will ensure that all strings having the same content share the same memory. As soon as a String object is invoked with intern(), it first checks if the string value of the String object is already present in the string pool and if it is AVAILABLE, then the reference to that string from the string CONSTANT pool is returned. If not, a new string object is added to the string pool, and a reference to it is returned. Example: String str1 = new String("Scaler by InterviewBit").intern(); //LINE1 String str2 = new String("Scaler by InterviewBitt").intern(); //Line2 System.out.println(str1 == str); //prints trueAs you can see, the intern() method is invoked on the String objects. When Line1 is executed, memory is allocated within the SCP. In line 2, no new string objects are created in the SCP because str1 and str2 have the same content. As a result, the reference to the object created in line1 is returned. This MEANS that str1 and str2 both point to the same memory. Therefore, the print statement prints true. |
|