I fixed an endless loop by changing Integer to int in the following:
public class IntTest {
public static void main(String[] args) {
Integer x=-1;
Integer total=1000;
while(x != total){
System.out.println("x =" + x + "total ="+ total);
x++;
}
}
}
What is the proper reason for this? I figured Integer would compare no problem.
Thanks.
Because when you make != comparing on the object it compares the references. And the references between two objects in general case are different.
When you compare ints it always compares primitives, lets say not references( there are no objects ), but the values.
So, if you want to work with Integer you must use equals() on them.
Additionally, if your values are between 0 and 255 the comparison between Integer works fine, because of caching.
You can read here: http://download.oracle.com/javase/tutorial/java/data/numberclasses.html
Integer
is an Object
, and objects are compared with .equals(..)
Only primitives are compared with ==
That's the rule, apart from some exceptional cases, where ==
can be used for comparing objects. But even then it is not advisable.
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