Wednesday, August 3, 2011

How to compare Numbers in Java?

I have some Number objects (Longs or Doubles or something). How can I compare them without setting up a massive instance check?

Best Answer

If you use build-in Java Long or Double then you can use
Long.compareTo() or Double.compareTo() -- but these method only tell you if one is equal, greater, or less than other.

public static void main(String[] args) {
Long num1 = new Long((long)100);
Long num2 = new Long((long)200);
int comp = num1.compareTo(num2);
if(comp < 0)
System.out.println("num1 is smaller than num2");
else if(comp == 0)
System.out.println("num1 is equal num2");
else
System.out.println("num1 is greater than num2");
}

Produce "num1 is smaller than num2"

No comments: