3

Hi I had a question related to Integer comparison.

say I have two Integer count1 and count2, I want to implement the following action:

if (count1 bigger than count2)
    do something;
else
    do something else;

I know I can use count1.compareTo(count2) > 0. however, when count1 or count2 is a null value, program will return a NullPointerException. Is there a way to implement that if count1 or count2 is a null value, return false when doing comparison between count1 and count2?

Vortex
  • 147
  • 1
  • 2
  • 9

2 Answers2

5

I think you want:

if (count1 != null && count2 != null && count1 > count2)
    do something;
else
    do something else;

Java will auto un-box the Integer objects to int primitive values to make the mathematical > comparison.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

Is there a way to implement that if count1 or count2 is a null value, return false

if (count1 == null || count2 == null) return false;
if (count1 > count2)
   doSomething();
else
   doSomethingElse();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130