String comparison with logical operator in Java

前端 未结 7 1121
别那么骄傲
别那么骄傲 2020-12-03 23:59

When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo

7条回答
  •  感动是毒
    2020-12-04 00:03

    The magic is called interning.

    Java interns String literals and so there is a high probability that it evaluates to true:

    String a = "hello";       // "hello" is assigned *and* interned
    String b = "hello";       // b gets a reference to the interned literal
    if (a == b)
       System.out.println("internd.");
    
    String c = "hello" + Math.abs(1.0);   // result String is not interned
    String d = "hello" + Math.abs(1.0);   // result String is not interned
    System.out.println(c==d);             // prints "false"
    
    c = c.intern();
    System.out.println(c==d);             // prints "false"
    
    d = d.intern();
    System.out.println(c==d);             // prints "true"
    

提交回复
热议问题