In this article, we will discuss intern() method of String class which is used to return interned string
1. String’s intern() method:
- This String method is used to return canonical representation of String object
1.1 Method Signature:
public String intern();
1.2 Returns:
- Returns a canonical representation for the string object
1.3 Background about String storage area:
There are basically 2 areas where we can store string
- Heap memory in JVM
- String Literal pool
String stored at constant pool are referred as String Literal whereas string object created using new operator stored at heap memory
Q) Why there is a need for 2 separate areas for Strings ?
- Generally, everything in Java is object
- So, keeping in line with that string is also object (which can be created using new operator)
- At the same time, there is another storage area called String literal pool which maintains list of unique string values/contents thereby reducing space for string storage of same contents/values
- String constant pool is much faster when comparing with string object for operations like retrieval or string comparison
- And string is the most frequently used object in Java for sending & receiving information across network connection
- So to attain the feature of faster access/retrieval & comparison, Java has a separate arrangement for string object which can be stored inside String Literal pool
Q) Why there is an intern() method in String class ?
- Assume that, if there are numerous String objects and it is frequently accessed and made comparison with some other string object
- In this case, instead of comparing with equals() method, we can simply use “==” operator after interning the string
- So, for faster accessibility and comparison of any string object interned string can be used
- This is the main reason for introducing intern() method inside String class
Q) What happens exactly, when intern() method is invoked on any String object ?
When string object is interned, then
- It checks whether string object’s content already present inside String Literal pool
- If it is present, then simply reference is returned
- Otherwise, a new string is added to the string literal and its reference is returned
- For better understanding, go through below examples
- Note: all string inside string constant pool are self-interned
2. Examples on intern() method:
String literal is compared with String object after interning:
In the below example,
- define a simple string literal with value “Bench”
- now, again define a string object using new operator
- Compare 1: compare string literal with string object of same content which returns false because of different references
- Compare 2: After this, intern the string object and compare string literal with interned string which returns true because both refers to same string (or both pointing to same string with same reference)
- Note: equals() method compares string contents whereas “==” operator checks references of both strings
StringInternMethod.java
package in.bench.resources.string.methods;
public class StringInternMethod {
public static void main(String[] args) {
// string literal
String str1 = "Bench";
// string object using new operator
String str2 = new String("Bench");
// compare 1: string literal with string object
if(str1 == str2) {
System.out.println("Compare 1: String literal and "
+ "String object are same");
}
else {
System.out.println("Compare 1: String literal and "
+ "String object are NOT same");
}
// intern the string object using intern() method
// this create string object in String Constant pool
String str3 = str2.intern();
// compare 2: interned string object with string literal
if(str1 == str3) {
System.out.println("\nCompare 2: String literal and "
+ "interned String object are same");
}
else {
System.out.println("\nCompare 2: String literal and "
+ "interned String object are NOT same");
}
}
}
Output:
Compare 1: String literal and String object are NOT same
Compare 2: String literal and interned String object are same
For more read String Literal and String constant pool concept
Related Articles:
- Java – String charAt(int index) method
- Java – String compareTo(String anotherString) method
- Java – String compareToIgnoreCase(String str) method
- Java – String concat(String str) method
- Java – String contains(CharSequence s) method
- Java – String contentEquals(StringBuffer sb) method
- Java – String copyValueOf(char[] data) method (2)
- Java – String endsWith(String suffix) method
- Java – String equals(Object anObject) method
- Java – String equalsIgnoreCase(Object anObject) method
- Java – String format(String format, Object… args) method
- Java – String getBytes() method (4)
- Java – String getChars() method
- Java – String hashCode() method
- Java – String indexOf() method (4)
- Java – String intern() method
- Java – String isEmpty() method
- Java – String join() method (2)
- Java – String lastIndexOf() method (4)
- Java – String length() method
- Java – String matches(String regex) method
- Java – String regionMatches() method (2)
- Java – String replace(char oldChar, char newChar) method
- Java – String replace(CharSequence target, CharSequence replacement) method
- Java – String replaceAll(String regex, String replacement) method
- Java – String replaceFirst(String regex, String replacement) method
- Java – String split(String regex) method
- Java – String split(String regex, int limit) method
- Java – String startsWith(String prefix) method
- Java – String startsWith(String prefix, int toffset) method
- Java – String subSequence(int beginIndex, int endIndex) method
- Java – String substring(int beginIndex) method
- Java – String substring(int beginIndex, int endIndex) method
- Java – String toCharArray() method
- Java – String toLowerCase() method (2)
- Java – String toUpperCase() method (2)
- Java – String toString() method
- Java – String trim() method
- Java – String valueOf() method (9)
References:
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
Happy Coding !!
Happy Learning !!