简体   繁体   中英

Why == returns true?

Why this condition returns true, as we know == returns true if both of the variable has same reference, but here the reference is not same but still it is entering in the loop and prints Hello World.

String var1="hi";
String var2="hi";

if(var1==var2){
    System.out.println("Hello World");
}

Because Java has a pool of unique interned instances, and that String literals are stored in this pool. This means that the first "hi" string literal is exactly the same String object as the second "hi" literal.

当将字符串文字分配给变量时,由于字符串被缓存并且是不可变的,因此您很可能会获得对同一对象的引用,因此这些字符串实际上具有相同的引用。

When you assign a String literal to a String, that literal is stored as a String instance into memory. Further assignments of the same literal will point to the same memory location. So if var1 and var2 were declared of type String, then var1 == var2 will return true , because they point to the same String instance "hi" .

You have declared var1 and var2 as int instead of String.

My compiler refuses to compile the code, saying "incompatible types".

Your compiler probably casts the string "hi" into some number, for example 0, because the variables should have number values.

Refer jvm specifcation .

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.

由于这个http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5的实现,这里的大多数答案已经为您指明了正确的方向,但是最好这样做阅读真理之源。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM