Possible Duplicate:
Weird Java Boxing
Hi,
Can somebody explain why the last print returns false ?
int a = 100;
int b = 100;
System.out.println(a == b); // prints true
Integer aa = 100;
Integer bb = 100;
System.out.println(aa == bb); // prints true
Integer aaa = 1000;
Integer bbb = 1000;
System.out.println(aaa == bbb); // prints false
Thanks Michael
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.
The Java Object clone() method creates a shallow copy of the object. Here, the shallow copy means it creates a new object and copies all the fields and methods associated with the object. The syntax of the clone() method is: object.clone()
The reason why the second print evaluates to true is because the first 128 Integer objects are cached by the Integer class. You want to use .equals
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