71

Is it OK to compare an int and a long in Java...

long l = 800L
int i = 4

if (i < l) {
 // i is less than l
}
jotaEsse
  • 261
  • 2
  • 18
user1472813
  • 719
  • 1
  • 5
  • 3

2 Answers2

117

Yes, that's fine. The int will be implicitly converted to a long, which can always be done without any loss of information.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Just to add a scenario that came across. `int a = Integer.MAX_VALUE; long b = a;` the following gives false. `print(a + 1 > b)` Seems the implicit conversion happens after `a+1` is stored as an `int` – Weishi Z Jul 21 '16 at 07:06
  • @WeishiZeng: Yes, absolutely. Both operands in `a + 1` are `int` - so that addition happens in `int` arithmetic, then the conversion to `long`, then the comparison. – Jon Skeet Jul 21 '16 at 11:55
-5

You can compare long and int directly however this is not recommended.
It is always better to cast long to integer before comparing as long value can be above int limit

long l = Integer.MAX_VALUE;       //2147483647
int i = Integer.MAX_VALUE;        //2147483647
System.out.println(i == l);       // true
 l++;                             //2147483648
 i++;                             //-2147483648
System.out.println(i == l);       // false
System.out.println(i == (int)l);  // true
Manasi
  • 765
  • 6
  • 17
  • Why is it not recommended? –  Aug 08 '18 at 09:53
  • 2
    It is not better to cast long to integer before comparing, on the contrary, that can lead to overflow and thus to wrong results. – Mark Rotteveel Aug 08 '18 at 09:54
  • @intentionallyleftblank : it is not recommended because both have different range and even if we store same value in both variables output will be different. – Manasi Aug 08 '18 at 09:55
  • @MarkRotteveel : i completely agree casting long to int is not better however this scenario it is required, for overflow cases comparison only – Manasi Aug 08 '18 at 09:57
  • 4
    No it is not required in this scenario, it is even incorrect in this scenario. When comparing int and long, the int is automatically cast to long and that works correctly. Casting the long to int can lead to incorrect results, and is thus the wrong thing to do. Your example even points that out, because of course -2147483648 is not equal to 2147483648 – Mark Rotteveel Aug 08 '18 at 09:58
  • @MarkRotteveel : can you please explain me how can we compare int and long if we have case explained in my answer after l++ and i++ ?, logically they have same value – Manasi Aug 08 '18 at 10:01
  • 1
    The only thing your example points out is that the choice of `int` for `i` is the wrong choice, because the overflow shouldn't have happened. – Mark Rotteveel Aug 08 '18 at 10:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177625/discussion-between-manasi-and-mark-rotteveel). – Manasi Aug 08 '18 at 10:04