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
wizard2000Asked:
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.

StillUnAwareCommented:
You must use a.equals(b)
wizard2000Author Commented:
yes... but why!?
StillUnAwareCommented:
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

Your issues matter to us.

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

Start your 7-day free trial
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

StillUnAwareCommented:
here is the implementation of Integer.equals:

    public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
StillUnAwareCommented:
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
zzynxSr. 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.