Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 904
user1472813 Avatar asked Jun 21 '12 17:06

user1472813


People also ask

Can we compare long long and int?

int/long compare always works. The 2 operands are converted to a common type, in this case long and all int can be converted to long with no problems.

Can we use == to compare long in Java?

== compares references, . equals() compares values. These two Longs are objects, therefore object references are compared when using == operator. However, note that in Long id1 = 123L; literal value 123L will be auto-boxed into a Long object using Long.

Can you compare int and string in Java?

If you want to compare their string values, then you should convert the integer to string before comparing (i.e. using String. valueOf() method). If you compare as integer values, then 5 is less than "123". If you compare as string values, then 5 is greater than "123".

Can we compare long and long in Java?

longs can not be compared with ==. The theory states that you need to use a simple trick like subtracting the one from the other and see the relevant difference.


1 Answers

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

like image 58
Jon Skeet Avatar answered Oct 01 '22 04:10

Jon Skeet