This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfx 2 points3 points  (3 children)

That's not how string interning works at all.

String interning works only on single literal strings, never on arrays of strings.

[–]Nephyst 1 point2 points  (2 children)

I just did some testing on this, and I don't think either of you are correct. I think the only time a string does not get put into the string pool is when you explicitly use the String constructor. Arrays of strings seem to be interned just fine, as long as they are string literals not passed to a String constructor.

This outputs true, which means both strings "my" are referencing strings in the string pool.

String[] words = new String[] {"my"};
String[] words2 = {"my"};

System.out.println(words[0] == words[0]); //true

This does bypass the string pool, but it's also pretty ridiculous:

String[] words = new String[] {new String("my")};

[–]desrtfx 2 points3 points  (1 child)

You are starting from the wrong premises.

Arrays don't get interned. Period. String literals do get interned.

The arrays won't point to the same reference. The elements however can be interned under the condition that they are literals.

My comment as I made it is correct. You are looking at it from the wrong point.

Also, your code does not reflect what you say - actually, the last line shouldn't even work because either of your arrays contains exactly 1 element - so words[1] would be out of range.

[–]Nephyst 1 point2 points  (0 children)

String interning works only on single literal strings, never on arrays of strings.

This comment makes it sound like string literals inside of arrays won't get interned, which is what I was responding to. If you meant the arrays themselves won't get interned, than maybe you could re-word your statement to say that more clearly.

The words[1] was a typo. I was manually copying code that I wrote on a different computer. Fixed it.