In JDK 1.6, can String equals operation can be replaced with ==?

前端 未结 5 989
谎友^
谎友^ 2020-12-21 04:10

As I study the source code of some open source products, I find code like:

if (a==\"cluser\")

a is a String variable. Can a St

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 05:06

    From the Java Language Specification, section 3.10.5 String Literals

    Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions are "interned" so as to share unique instances, using the method String.intern.

    Thus, the test program consisting of the compilation unit:

    package testPackage;
    class Test {
            public static void main(String[] args) {
                    String hello = "Hello", lo = "lo";
                    System.out.print((hello == "Hello") + " ");
                    System.out.print((Other.hello == hello) + " ");
                    System.out.print((other.Other.hello == hello) + " ");
                    System.out.print((hello == ("Hel"+"lo")) + " ");
                    System.out.print((hello == ("Hel"+lo)) + " ");
                    System.out.println(hello == ("Hel"+lo).intern());
            }
    }
    class Other { static String hello = "Hello"; }
    

    and the compilation unit:

    package other;
    
    public class Other { static String hello = "Hello"; }
    

    produces the output:

    true true true true false true
    

    This example illustrates six points:

    1. Literal strings within the same class in the same package represent references to the same String object.
    2. Literal strings within different classes in the same package represent references to the same String object.
    3. Literal strings within different classes in different packages likewise represent references to the same String object.
    4. Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
    5. Strings computed by concatenation at run time are newly created and therefore distinct.
    6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

提交回复
热议问题