Java String intern() method is used for getting the string from the memory if it is already present. This method ensures that all the same strings share the same memory. For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance.
A Simple Java String intern() method example
This example demonstrates the use of intern() method. This method searches the memory pool for the mentioned String, if the string is found then it returns the reference of it, else it allocates a new memory space for the string and assign a reference to it.
public class Example{ public static void main(String args[]){ String str1 = "beginnersbook"; /* The Java String intern() method searches the string "beginnersbook" * in the memory pool and returns the reference of it. */ String str2 = new String("beginnersbook").intern(); //prints true System.out.println("str1==str2: "+(str1==str2)); } }
Output:
str1==str2: true
Java automatically interns String literals
When we create Strings using string literals instead of creating them using new keyword then the java automatically interns String them. Lets take an example to understand this:
public class Example{ public static void main(String args[]){ String str1 = "Hello"; //Java automatically interns this String str2 = "Hello"; //This is same as creating string using string literal String str3 = "Hello".intern(); //This will create a new instance of "Hello" in memory String str4 = new String("Hello"); if ( str1 == str2 ){ System.out.println("String str1 and str2 are same"); } if ( str2 == str3 ){ System.out.println("String str2 and str3 are same" ); } if ( str1 == str4 ){ //This will not be printed as the condition is not true System.out.println("String str1 and str4 are same" ); } if ( str3 == str4 ){ System.out.println("String str3 and str4 are same" ); } } }
Output:
String str1 and str2 are same String str2 and str3 are same String str3 and str4 are same
Related Posts:
- Java String format() method
- Java String matches() method
- Java String trim() and hashCode() methods
- Java String replace(), replaceFirst() and replaceAll() methods
Leave a Reply