The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool.

Note that, if another String with the same contents exists in the String constant pool, then a new object won’t be created and the new reference will point to the other String.

Available Signatures

public String intern()

Example

@Test
public void whenIntern_thenCorrect() {
    String s1 = "abc";
    String s2 = new String("abc");
    String s3 = new String("foo");
    String s4 = s1.intern();
    String s5 = s2.intern();
    
    assertFalse(s3 == s4);
    assertTrue(s1 == s5);
}
Next »
Java String.isEmpty()
« Previous
Java String.indexOf()
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.