I'm a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API. I have the following code:
if (count.compareTo(0)) { System.out.println(out_table); count++; }
This is inside a loop and just outputs out_table
.
My goal is to figure out how to see if the value in integer count > 0
.
I realize the count.compare(0)
is the correct way? or is it count.equals(0)
?
I know the count == 0
is incorrect. Is this right? Is there a value comparison operator where its just count=0
?
Syntax : public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero. Example :To show working of java.
Integer. compare() compares two int values numerically and returns an integer value. If x>y then the method returns an int value greater than zero. If x=y then the method returns zero.
In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
To figure out if an Integer
is greater than 0, you can:
check if compareTo(O)
returns a positive number:
if (count.compareTo(0) > 0) ...
But that looks pretty silly, doesn't it? Better just...
use autoboxing1:
if (count > 0) ....
This is equivalent to:
if (count.intValue() > 0) ...
It is important to note that "==
" is evaluated like this, with the Integer
operand unboxed rather than the int
operand boxed. Otherwise, count == 0
would return false when count
was initialized as new Integer(0)
(because "==
" tests for reference equality).
1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int
to compareTo
) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.
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