String pooling is a process in which a single copy of each distinct string value is stored. Otherwise, strings are immutable. This way the strings can contain the same data and share the same memory. In this way, the memory required will be greatly reduced.
When the 'intern' function is called:
It checks for equality between two strings - i.e. whether the string object exists in the string constant pool ( SCP).
If available, the string will be obtained from the pool and returned. Otherwise, a new string object is created and added to the pool. A reference to the string object is also returned.
For two strings 'a' and 'b', if and only if a.equals(b) returns true, a.intern() == b.intern( ) is true.
Let’s look at an example:
Demonstration
public class Demo{ public static void main(String[] args){ String s1 = new String("Its"); String s2 = s1.concat("sample"); String s3 = s2.intern(); System.out.println("Checking equality of object 2 and 3 :"); System.out.println(s2 == s3); String s4 = "Its a sample"; System.out.println("Checking equality of object 3 and 4 :"); System.out.println(s3 == s4); } }
Checking equality of object 2 and 3 : true Checking equality of object 3 and 4 : false
A file named The Demo class contains the main function. Three instances of String objects are defined here, where the second string is the concatenation of the first string with different values. The third string is calling the ' intern ' function on the second string. These strings are compared using the '==' operator and the results are displayed on the console.
The above is the detailed content of In Java, the implementation of string. For more information, please follow other related articles on the PHP Chinese website!