Interned String

Basics.

Why String interning?

Examples

	// value of str1 is known at compile time, so, its automatically interned.
	String str1 = "abcdef";  
	
	// same as above
	String str2 = "abc"; 
	
	// same as above
	String str3 = "def" ; 
	
	// str4 is also "abcdef", but it is not equal to str1 by using "==" operator, 
	// since the value of str4 is only known at runtime.
	String str4 = str2+str3;
	
	// str5 is also "abcdef", but it is equal to str1 by using "==" operator
	String str5 = str4.intern(); 
	
	// value of str6 is same as str1, and since the values of both are known at compile time, 
	// they are interned by default and are equal using "==" operator.
	String str6 = "abcdef"; 

	// prints false;
	System.out.println(str1 == str4);
	
	// prints true;
	System.out.println(str1 == str5);
	
	// prints true;
	System.out.println(str1 == str6);
	
	// prints true, but is O(N);
	System.out.println(str1.equals(str4));
	
	// prints true, but is O(N);
	System.out.println(str1.equals(str5));
	
	// prints true, but is O(N);
	System.out.println(str1.equals(str6)); 

Recap

References