Punter Vicky
Punter Vicky

Reputation: 16982

Why is String created from Char Array not interned?

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

Upvotes: 1

Views: 143

Answers (1)

Michał Krzywański
Michał Krzywański

Reputation: 16900

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.

Upvotes: 2

Related Questions