Total Pageviews

2018/07/06

[Java] How to compare two Integers in Java?

Problem
Here has a sample code to compare two Integers, why it return false?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  package test.albert;
  
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class App {
      public static void main(String[] args) {
          Integer num1 = 554;
          Integer num2 = 554;
          Boolean result = num1 == num2;
          log.debug("compare result = " + result);
      }
  }

How-To
Owing to == between Integer will check for its reference equality, so it will return false.
If you would like to compare with its value, you need to get its intValue().

Here has the updated sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  package test.albert;
  
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class App {
      public static void main(String[] args) {
          Integer num1 = 554;
          Integer num2 = 554;
          Boolean result = (num1.intValue() == num2.intValue());
          log.debug("compare result = " + result);
      }
  }


No comments: