英文:
500 != 500 java Integer please explain
问题
public class Demo {
public static void main(String[] arr) {
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = 500;
Integer num4 = 500;
System.out.println(num3 == num4);
if (num1 == num2) {
System.out.println("num1 == num2");
} else {
System.out.println("num1 != num2");
}
if (num3 == num4) {
System.out.println("num3 == num4");
} else {
System.out.println("num3 != num4");
}
}
}
输出:
false
num1 == num2
num3 != num4
为什么第二个 if 语句(即 num3 == num4)返回 false,即使这两个数字都是相同的值 500,请解释。
英文:
public class Demo{
public static void main(String[] arr){
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = 500;
Integer num4 = 500;
System.out.println(num3==num4);
if(num1==num2){
System.out.println("num1 == num2");
}
else{
System.out.println("num1 != num2");
}
if(num3 == num4){
System.out.println("num3 == num4");
}
else{
System.out.println("num3 != num4");
}
}
}
the o/p:
false
num1 == num2
num3 != num4`
why is the 2nd if statement i.e(num3 == num4) false where both number has the same value 500 please explain
答案1
得分: 1
整数是一个对象,需要使用 equals
方法进行比较。直接使用 ==
运算符会比较引用,即是否指向同一个对象,这不是您想要实现的内容。关于 num1 == num2
,请查看 此链接 获取详细信息。在 Java 中,小的数字被临时保存以节省内存。因此,当比较 num1
和 num2
时,它们实际上引用的是同一个对象。而对于 num3
和 num4
,它们分别引用独立的对象。
英文:
Integer is an Object and need to use equals
to compare. Direct ==
is comparing the reference whether pointing the same object, which is not what you want to achieve. Regarding the num1 == num2, please check this link for details. Small numbers are interim to save memory in Java. So when comparing num1
and num2
they are actually referring the same object. While num3
and num4
they refer stand-alone objects respectively.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论