Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java == operator [duplicate]

Tags:

java

operators

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

like image 672
Michael Ellick Ang Avatar asked Aug 17 '10 19:08

Michael Ellick Ang


People also ask

What does == in Java do?

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.

Can you use == to compare objects in Java?

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).

What is the difference between == vs equals () in Java?

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.

What is clone () in Java?

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()


1 Answers

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

like image 106
Amir Afghani Avatar answered Sep 28 '22 03:09

Amir Afghani