public static void main(String[] args) {
String one = "hello";
String two = "hello";
if (one == two) {
System.out.println("they are the same objects");
} else {
System.out.println("they are different objects");
}
String three = new Integer(76).toString();
String four = "76";
if (three == four) {
System.out.println("they are the same objects");
} else {
System.out.println("they are different objects");
}
String five = new Integer(76).toString().intern();
String six = "76";
if (three == four) {
System.out.println("they are the same objects");
} else {
System.out.println("they are different objects");
}
}
コンソールは結果を出力します:
they are the same objects
they are different objects
they are the same objects
実際、最新の仮想マシンは非常に効率的で賢いです。また、作成中のオブジェクトが共有されないこと、つまり、作成されたコードブロックの外に出ないことを検出した場合、仮想マシンは実際にそのオブジェクトをスタックに作成します。私たちはそれを見ることはなく、私たちが書くものにも影響を与えません。
Javaではオブジェクトの作成場所を制御できませんが、実際には、仮想マシンが最も効率的な選択になります。したがって、コードは通常、最適化された方法で実行されます。
Javaは、オブジェクト3用に作成した文字列をオブジェクト4用に再利用できませんでした。これは、オブジェクト3の文字列が、仮想マシンにその文字列をプールに配置させることができなかったためです。
とにかくJavaは自動的に小さな文字列をプールに配置するので、プールに配置されないのはこれらの計算された文字列だけです。
さて、インターンを使用する理由は、もちろん、頻繁に再利用される文字列をプールに入れる方がよいためです。これにより、作成されるオブジェクトの数が最小限に抑えられ、ガベージコレクションが必要になります。