Popular Tutorials
Start Learning JavaCreated with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Java String Methods
- Java String split()
- Java String compareTo()
- Java String compareToIgnoreCase()
- Java String length()
- Java String replace()
- Java String replaceAll()
- Java String substring()
- Java String equals()
- Java String equalsIgnoreCase()
- Java String contains()
- Java String indexOf()
- Java String trim()
- Java String charAt()
- Java String toLowerCase()
- Java String concat()
- Java String valueOf()
- Java String matches()
- Java String startsWith()
- Java String endsWith()
- Java String isEmpty()
- Java String intern()
- Java String getBytes()
- Java String contentEquals()
- Java String hashCode()
- Java String join()
- Java String replaceFirst()
- Java String subSequence()
- Java String toCharArray()
- Java String format()
Java String intern()
The syntax of the string intern() method is:
string.intern()
Here, string is an object of the String class.
intern() Parameters
The intern() method does not take any parameters.
intern() Return Value
- returns a canonical representation of the string
What is Java String Interning?
The String interning ensures that all strings having the same contents use the same memory.
Suppose, we these two strings:
String str1 = "xyz";
String str2 = "xyz";
Since both str1 and str2 have the same contents, both these strings will share the same memory. Java automatically interns the string literals.
However, if you create strings with using the new keyword, these strings won't share the same memory. For example,
class Main {
public static void main(String[] args) {
String str1 = new String("xyz");
String str2 = new String("xyz");
System.out.println(str1 == str2); // false
}
}
As you can see from this example, both str1 and str2 have the same content. However, they are not equal because they don't share the same memory.
In this case, you can manually use the intern() method so that the same memory is used for strings having the same content.
Example: Java String intern()
class Main {
public static void main(String[] args) {
String str1 = new String("xyz");
String str2 = new String("xyz");
// str1 and str2 doesn't share the same memory pool
System.out.println(str1 == str2); // false
// using the intern() method
// now both str1 and str2 share the same memory pool
str1 = str1.intern();
str2 = str2.intern();
System.out.println(str1 == str2); // true
}
}
As you can see, both str1 and str2 have the same content, but they are not equal initially.
We then use the intern() method so that str1 and str2 use the same memory pool. After we use intern(), str1 and str2 are equal.
