user1472813
user1472813

Reputation: 789

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

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
}

Upvotes: 78

Views: 69663

Answers (2)

Manasi
Manasi

Reputation: 765

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

Upvotes: -5

Jon Skeet
Jon Skeet

Reputation: 1500505

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

Upvotes: 124

Related Questions