# comparing integers

Hi

why is this code not working?

Integer a = new Integer(23);
Integer b = new Integer(23);

if(a==b) {
System.out.println('matched!');
}

the integer values are the same, but they never match!
LVL 1
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You must use a.equals(b)
Author Commented:
yes... but why!?
Commented:
if You use '==' sign it returns whether the objects are equal and
equals returns true also when the values contained in objects are equal

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
here is the implementation of Integer.equals:

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
Commented:
sorry, not fully posted:

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

As You can see, it checks for Integer object, then returns if the values are equal
Sr. Software engineerCommented:
I know it's already closed, but...
if you use '==', you check if the two instances are the same.
So, since a is another Integer object than b, it returns false.
This would return true:

Integer a = new Integer(23);
Integer b = a;

if(a==b) {
System.out.println("matched!");
}
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.