Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two primitive long variables in java

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)
like image 930
Dragan Avatar asked Mar 13 '12 19:03

Dragan


People also ask

How do you compare two long variables in Java?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object. It returns false if both the objects are not same.

How do you compare two primitive data types in Java?

Primitives. Like in other languages, we can compare the values of primitives with the < , > , <= , and >= operator. The same problems of floating-point data types apply to them, so be aware. Also, boolean isn't comparable except for equality with == and !=

Can we compare long and long in Java?

The java. lang. Long. compareTo() method compares two Long objects numerically.


1 Answers

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);
}
like image 132
Another_Dev Avatar answered Sep 18 '22 13:09

Another_Dev