[英]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. 为什么这个条件返回true,因为我们知道==如果两个变量都具有相同的引用,则返回true,但是这里的引用不相同,但仍在循环中输入并打印Hello World。
String var1="hi";
String var2="hi";
if(var1==var2){
System.out.println("Hello World");
}
当将字符串文字分配给变量时,由于字符串被缓存并且是不可变的,因此您很可能会获得对同一对象的引用,因此这些字符串实际上具有相同的引用。
When you assign a String literal to a String, that literal is stored as a String instance into memory. 当您将String文字分配给String时,该文字将作为String实例存储到内存中。 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"
. 因此,如果
var1
和var2
声明为String类型,则var1 == var2
将返回true
,因为它们指向同一个String实例"hi"
。
You have declared var1 and var2 as int instead of String. 您已将var1和var2声明为int而不是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. 您的编译器可能会将字符串“ hi”强制转换为某个数字,例如0,因为变量应该具有数字值。
Refer jvm specifcation . 请参阅jvm规范 。
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. 使用String.intern方法,对字符串常量(或更一般地说,是常量表达式的值(第15.28节)的字符串)进行“ interned”,以便共享唯一的实例。
由于这个http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5的实现,这里的大多数答案已经为您指明了正确的方向,但是最好这样做阅读真理之源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.