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

JavaLong Integer

Java Problem Overview


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
}

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1472813View Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaManasiView Answer on Stackoverflow