Why is String created from Char Array not interned?

Punter Vicky :

Why is the String created from char array not interned?

jshell> var a = "Hello"
a ==> "Hello"

jshell> var b = "Hello"
b ==> "Hello"

jshell> a == b
$67 ==> true

jshell> char[] c = {'H','e','l','l','o'}
c ==> char[5] { 'H', 'e', 'l', 'l', 'o' }

jshell> var d = String.copyValueOf(c)
d ==> "Hello"

jshell> a == d
$70 ==> false
michalk :

This is because String iterals are only interned by default.

String::copyValueOf internally returns new String :

public static String copyValueOf(char[] var0) {
    return new String(var0);
}

so you would have to call intern on your String that is returned from this method and this will return a reference to this String in the String pool.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327930&siteId=1