-1
for (int i = 0; i< expArray.length; i++){
            System.out.println(expArray[i]);
            if ( expArray[i] == "5" ){  ///WHY IS THIS NOT WORKING!!!??             
                System.out.println("here");

I know the output of the System.out...:

0
=
0
+
5

This is how my String array was made:

    for (int i = 0; i< expArray.length; i++){
        if(varTable.get(expArray[i]) != null){
            expArray[i] =  Integer.toString((int) varTable.get(expArray[i]));
        }
    }

So the issue is, at the expArray[i] == "5" ) if block up top its not going in at i=1 where it should. any reason/thoughts?

dsuma
  • 1,000
  • 2
  • 9
  • 30
  • Description might help :[Why doesn’t == work on String](http://stackoverflow.com/questions/17443201/why-doesnt-work-on-string/17443215#17443215) – Suresh Atta Nov 22 '13 at 09:15

5 Answers5

5

Use nullsafe check, if you have a constant

if("5".equals(expArray[i]))
Alex K.
  • 3,294
  • 4
  • 29
  • 41
4
Use .equals() instead of == for String comparison!

== compares if both references point to the same object or not which is not your case. .equals() checks the actual String content.

For detailed explanation on String comparison check out this SO answer.

Community
  • 1
  • 1
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
3

Should use equals instead of ==

if(expArray[i].equals("5"))
Masudul
  • 21,823
  • 5
  • 43
  • 58
2

== is bad for comparing Strings (any objects really, unless you know they're canonical). == just compares object references. .equals() tests equality. For Strings, often they'll be the same but as you've discovered that's not guaranteed.

In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object references, not the content.

So, use if(expArray[i].equals("5"))

Linga
  • 10,379
  • 10
  • 52
  • 104
1

DO NOT COMPARE String using ==

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64