user1472813
user1472813

Reputation: 799

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: 79

Views: 69976

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: 1503749

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

Upvotes: 125

Related Questions