Java == for String objects ceased to work?

前端 未结 11 1022
情深已故
情深已故 2021-01-02 04:13
  public class Comparison {
        public static void main(String[] args) {
            String s = \"prova\";
            String s2 = \"prova\";
            System.         


        
相关标签:
11条回答
  • 2021-01-02 04:44

    JLS, 3.10.5 => It is guaranteed that a literal string object will be reused by any other code running in the same virtual machine that happens to contain the same string literal

    0 讨论(0)
  • 2021-01-02 04:44
    String s = "prova";
    String s2 = "prova";
    

    s and s2 are literal strings which are pointing the same object in String Pool of JVM, so that the comparison returns true.

    0 讨论(0)
  • 2021-01-02 04:45

    Source code literals are part of a constant pool, so if the same literal appears multiple times, it will be the same object at runtime.

    0 讨论(0)
  • 2021-01-02 04:50

    The JVM may optimize the String usage so that there is only one instance of the "equal" String in memory. In this case also the == operator will return true. But don't count on it, though.

    0 讨论(0)
  • 2021-01-02 04:53

    Ideally it should not happen ever. Because java specification guarantees this. So I think it may be the bug in JVM, you should report to the sun microsystems.

    0 讨论(0)
  • 2021-01-02 04:54

    You must understand that "==" compares references and "equals" compares values. Both s and s1 are pointing to the same string literal, so their references are the same.

    0 讨论(0)
提交回复
热议问题