1
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

Md Zafar Hassan
  • 284
  • 3
  • 13
  • Don't compare `Integer` objects using `==`. Only compare *objects* using `equals()`. If you wanted `==` comparison, you should have used the `int` primitive type. – Andreas Sep 17 '20 at 03:54

1 Answers1

1

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.

Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83