500 != 500 java Integer请解释

huangapple go评论68阅读模式
英文:

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 中,小的数字被临时保存以节省内存。因此,当比较 num1num2 时,它们实际上引用的是同一个对象。而对于 num3num4,它们分别引用独立的对象。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月17日 11:43:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63930948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定