Compare two primitive long variables in java
in java,
use ==
to compare primitives and x.equals(y)
to compare objects.
I'm not sure what your question is-- it looks like you tried both, and did neither work?
Note, you are using Long
instead of long
, so you want to use .equals()
(long
is a primitive, Long
is an object)
In java:
- the
==
operator tells you if the two operands are the same object (instance). - the
.equals()
method onLong
tells you if they are equal in value.
But you shouldn't do either. The correct way to do it is this:
assertEquals(id1, id2);
With assertEquals()
, if the assertion fails, the error message will tell you what the two values were, eg expected 2, but was 5
etc
Try doing the following:
assertTrue(id1.longValue() == id2.longValue())
To compare two primitive long you can simply use ==
Example:
long x = 1L;
long y = 1L;
if (x == y) {
System.out.println("value of x and y are same");
}
To compare two Long objects you can use Long.compare(long x, long y). This method was added in java 1.7. Below is the method implementation:
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Example:
Long x = new Long(1);
Long y = new Long(1);
if (Long.compare(x,y) == 0) {
System.out.println(values of x and y are same);
}