0

Anybody ever seen the following statement running false ?

String BloodyHell = "Unbelievable";
if (BloodyHell == BloodyHell) >> false

Although instead of bloody hell, I've got: |-,-| or |o,-| or |-,o| or |o,o| or XXXX.

None of these comes TRUE though. While debugging the exact thing is still false.

Somebody please help me out here. Here's the snippet:

public String doStats()
{       
        String[] pattern = splitPattern();          
        for (int i = 0; i < pattern.length; i++)
        {
            if (pattern[i] == "|-,-|")
                frontClosed++;
            if (pattern[i] == "|o,-|")
                left++;
            if (pattern[i] == "|-,o|")
                right++;
            if (pattern[i] == "|o,o|")
                frontOpened++;
            if (pattern[i] == "XXXX")
                noFace++;           
        }
}

enter image description here

Jake
  • 169
  • 2
  • 16
  • http://stackoverflow.com/a/4700501/1052673 – Nate Chandler Apr 10 '13 at 00:16
  • 3
    You need to be careful of the broad examples you make. `BloodyHell == BloodyHell` will *always* be true: http://ideone.com/ag6A29 – Cat Apr 10 '13 at 00:18
  • I believe the first thing they talk about in Java books and tutorials is about the use of `equals()` and explaining the reasons for it? re. question poster – Chris Dennett Apr 10 '13 at 00:22

2 Answers2

3

In Java you should use the String#equals method to compare string values instead of ==. The == operator compares object references to see if they are the same object, which is why you keep getting false. The object references are different, even if the contents of the strings are equivalent.

if (pattern[i].equals("|-,-|"))
rgettman
  • 176,041
  • 30
  • 275
  • 357
3

There is a difference between == and equals().

When comparing strings, you want to use equals(); == is used to compare if they are the same thing in memory.

BlackBox
  • 2,223
  • 1
  • 21
  • 37