3 ms·
I think op meant "String literals". For those the spec seems to require interning: > Moreover, a string literal always refers to the same instance of class Str
by maverwa 3y ago
I think op meant "String literals". For those the spec seems to require interning:
> Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
And later:
> Literal strings within different classes in different packages likewise represent references to the same String object.
Source: https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5 https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html...
But that does - as far as I can see - say nothing for non-literal strings.
[edit]: formatting
- 3cats-in-a-coat 3y agoThanks, makes sense yes. Still if the JVM look up in all cases defers to value after ref mismatch, it should work identically, no? Even if interning is mandatory as per spec, I'm not sure how it'd change the outcome of evaluation.
- maverwa 3y agoyeah, I'd assume as much. If it indeed falls back to a by-value comparison it would be slower, but should work.
- xxs 3y agonope - it'd be plain wrong. Literals must be equal by reference, comparing them by value would just break JLS, as they would be equal to any other composed string by reference as well.
- robertlagrant 3y agoYes - that is a performance optimisation. I don't think comparing everything by value makes or breaks the implementation.
- xxs 3y ago>I don't think comparing everything by value makes or breaks the implementation. Nothing much to think -- distinct objects must have distinct references [e.g. new String("a")!=new String("a')], literals must have the same references for the same values [e.g. "a"=="a"].
- robertlagrant 3y agoWhy does it break the implementation, other than performance?
- thfuran 3y agoIt affects the result of ==, which is only a reference comparison.
- simiones 3y agoThe problem is that, per the spec, the following must hold: if("abc" == "abc") { System.out.println("correct"); } if(new String("abc") != new String("abc")) { System.out.println("correct"); } So, not having proper string interning support means that you mis-execute certain programs.
- kelnos 3y agoSure, but also consider that this JVM (intentionally) lacks support for other things that all but the most trivial programs would use. I don't think it's expected by the author that you can throw any random program at it. It's really there just to run your own programs that you've written specifically for it in order to play around with things. And since you know you're writing for this particular JVM, you should know not to do anything that depends on string interning, among other things.
- xxs 3y agopretty much indeed. > say nothing for non-literal strings yes, of course.