Java String intern() Method
Example
Compare two strings with ==, without and with intern():
public class Main {
public static void main(String[] args) {
String myStr1 = "Hello";
String myStr2 = new String("Hello");
System.out.println(myStr1 == myStr2);
System.out.println(myStr1 == myStr2.intern());
}
}
Definition and Usage
The intern() method returns the string from the string pool (a place in memory where Java keeps one copy of each string literal, like "Hello"). If the pool does not have the string yet, Java adds it first.
Strings with the same text that come from the pool are the same object, so == returns true for them.
Tip: To compare the text of two strings, use the equals() method. The == operator only checks if two variables point to the same object.
Syntax
public String intern()
Parameter Values
None.
Technical Details
| Returns: | A string with the same text, taken from the string pool. |
|---|
Related Pages
❮ String Methods