Java – Compare two primitive long variables in java

comparejavalong-integer

The title is pretty self-explanatory. I'm moving from C# to Java. I have an object and a getter method which returns its ID. I want to compare the ids of two objects of the same type and check if the values of their ids are equal.

tried:

obj.getId() == obj1.getId();

Long id1 = obj.getId();
Long id2 = obj1.getId();

assertTrue(id1.equals(id2))

assertTrue(id1== id2)

Best Solution

In java:

  • the == operator tells you if the two operands are the same object (instance).
  • the .equals() method on Long 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