๋ฌธ์์ด ๋ฆฌํฐ๋ด๊ณผ ๋ฌธ์์ด ๊ฐ์ฒด ๊ด๋ จํด์ ์ง๋ฌธ์ด ์์ต๋๋ค.
๋ฐ๋ผ์ intern()์ ๊ฒฝ์ฐ์๋ ๋ค์ ํ๋ฆ์ฒ๋ผ ์๋๋ ๊ฒ์ด๋ผ ์๊ฐ์ ํ์ต๋๋ค.public class Main { public static void main(String[] args) { // ๋ฌธ์์ด ๋ฆฌํฐ๋ด s1๋ JVM Heap ์์ญ์ String Constant Pool์ ์ ์ฅ๋๋ค. // s2๋ ๋ฌธ์์ด ๋ฆฌํฐ๋ด์ ์กด์ฌํ๋ "hello" ๋ฌธ์์ด์ ์ฐธ์กฐํ๋ค. String s1 = "hello"; String s2 = "hello"; System.out.println(s1.equals(s2)); // true System.out.println(s1 == s2); // true // ๋ฌธ์์ด ์์ ํ์ "hello" ๋ฌธ์์ด์ด ์กด์ฌํ๋ฏ๋ก, // ๋ฌธ์์ด ์์ ํ๋ก๋ถํฐ ๋ฌธ์์ด ๊ฐ์ฒด๋ฅผ ๊ฐ์ ธ์จ๋ค. System.out.println(s1.intern()); // hello System.out.println(); // s3์ s4๋ JVM Heap ์์ญ์ ์ ์ฅ๋๋ค. String s3 = new String("hello"); String s4 = new String("hello"); System.out.println(s3.equals(s4)); // true System.out.println(s3 == s4); // false, JVM Heap์ ์ ์ฅ๋ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์๊ฐ ๋ค๋ฅด๋ค. System.out.println(); System.out.println(s1 == s3); // false, JVM Heap์ ์ ์ฅ๋ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์๊ฐ ๋ค๋ฅด๋ค. System.out.println(s1.equals(s3)); // true, ๋ฌธ์์ด ๊ฐ์ด ์ผ์นํ๋ค. } }