-2

OK, my first question in stackOverflow.

This is something that I left me completely baffled.

Java (I use android Studio), I write the following code:

    Integer aNumber = 200;
    String aNumberInString;
    aNumberInString = Integer.toString(aNumber);
    Boolean result;
    if(aNumberInString == "200"){
        result = true;
    } else {
        result = false;
    }

    Log.i("result:",result+"");

OK, logic and what I expect is that the condition is true... But NO! it fails.

I was really shocked by this behavior, then investigate a little more, and run the code in debug mode step by step.

when I get to the condition, I inspect the value of "aNumberInString" and to my surprise, this is what I find:

SampleCode1

OK, so the first thing I think is: "Integer.toString ()" are doing something wrong.

Let's try another way: "String.valueOf ()"

Run in debug mode, and: SampleCode2

THE SAME! and fails, of course.

Obviously fails because it compares different characters, and in Internet I found a way to fix it,

string.replace ("\\ u0000", "");

but my question is not how to fix it, is:

Why is this happening?

Is there a correct way to prevent this from happening?

From already thank you very much to all, Regards, Nicolas

  • 1
    don't use `==` for string comparisons, use `equals()` – Ramanlfc Dec 30 '15 at 17:38
  • 1
    Just a small note: your interpretation of the debug display is wrong: `aNumberString` contains the chars '2', '0' and '0' from offset 8, and that is the fields `offset` (8) and `count` (3) show. – Thomas Kläger Dec 30 '15 at 18:23

1 Answers1

0

You are doing a reference comparison. For comparing Strings, you need to call equals. By doing == with an Object, you are asking Java to make sure they are the same object, not if they have the same value.

Change:

if(aNumberInString == "200"){

To this:

if(aNumberInString.equals("200") {

Or better yet, to reduce the chance of a NullPointerExcpetion:

if("200".equals(aNumberInString))
Todd
  • 30,472
  • 11
  • 81
  • 89