-1

Possible Duplicate:
How do I compare strings in Java?

I have a boolean statement that should evaluate to true due to the incorrect use of != to compare strings:

public int calculateWeight( String hostname, String parameter, 
         String parInstance ) throws InvalidWeightException
{
    if ( parameter != "*" && hostname != "*" && parInstance != "*" )
    {
        return 1;
    }
    ...
}

When debugging a JUnit test that calls this method, the if statement is evaluating to true (via Eclipse Inspect) yet the return statement does not execute. The value passed to parInstance variable is actually "*". If we use !(.equals()), the Eclipse Inspect shows false as expected.

Community
  • 1
  • 1
Doug Saus
  • 49
  • 1
  • 6
  • String caches some short strings, so when you use a string literal it might return the same String instead of a new one. – Paul Tomblin Nov 14 '12 at 17:52
  • 1
    regardless of == vs equals(), why have you switched from comparing not equal (!=) to equal (equals(), not !equals())? – mcalex Nov 14 '12 at 17:57
  • Ok, first, I know this code is broken. I don't want to fix the code. It is a defect and we are doing test driven development here so we are writing a junit to PROVE it is broken. However, the JUnit PASSES because the expression, which should evaluate to true (and upon eclipse debugger inspection DOES in fact evaluate to true) is actually skipping out of the if AS IF it had returned false. Why would the eclipse debugger's Inspect be showing it expression as 'true' and yet when I step to the next line, it does NOT execute the body of the if? That is the problem. – Doug Saus Nov 14 '12 at 18:59

1 Answers1

0

Look up the operator binding on != vs && and parenthesize.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • Parentheses would aid reading, but `!=` binds more tightly than `&&`, so the logic is correct: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Duncan Jones Nov 14 '12 at 18:21