I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

This article is part of a series:
• Java String.String()
• Java String.intern()
• Java String.codePointCount()
• Java String.codePointAt()
• Java String.concat()
• Java String.contains()
• Java String.copyValueOf()
• Java String.endsWith()
• Java String.format()
• Java String.getBytes()
• Java String.indexOf()
• Java String.intern()
• Java String.isEmpty()
• Java String.lastIndexOf()
• Java String.regionMatches()
• Java String.replace()
• Java String.replaceAll()
• Java String.split()
• Java String.startsWith()
• Java String.subSequence()
• Java String.substring()
• Java String.toLowerCase()
• Java String.toUpperCase()
• Java String.trim()
• Java String.valueOf()

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);
}

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS