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 }
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.
== 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.
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".
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.
Yes, that's fine. The int
will be implicitly converted to a long
, which can always be done without any loss of information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With