0

I seem to be having a problem with a boolean test. when I use this code:

public boolean setPkg (String inPkg)
    {
        boolean isValid;

        if ((inPkg.toUpperCase() != "A" ) || (inPkg.toUpperCase() != "B" ) || (inPkg.toUpperCase() != "C"))
            isValid = false;
        else
        {
            pkg = inPkg;
            isValid = true;
        }

        return isValid;
    }

It returns false on "A". However when I only test for "A":

...
if (inPkg.toUpperCase() != "A" ) 
isValid = false;
            else
            {
                pkg = inPkg;
                isValid = true;
            }

            return isValid;
...

it returns true.

what am I missing?

I have also tried to use multiple if else statements to test for A, B, or C and i get false for A. B and C dont get tested as an exception of my making is getting thrown.

user2175782
  • 95
  • 1
  • 1
  • 3
  • Just to add to the answers already there, when you use == on objects in java you're comparing the objects to see if they're the same object. String literals in Java like "foo" or "Bar" become fully fledged Java objects. You need to use the .equals() which compares the CONTENTS of the String objects, NOT whether or not they are the same object. – Jazzepi Mar 23 '13 at 20:11

4 Answers4

1

Two things over here :

  1. replace != with equals method for comparison
  2. replace || with &&
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
  • 1
    This is the only answer that mentioned that the user was trying to check like `string != 'A' || string != 'B'`. The condition would always return true. – Joshua Taylor Oct 15 '13 at 22:44
0

Always use oneString.equals(otherString), not oneString == otherString, when comparing strings.

For example, instead of:

(inPkg.toUpperCase() != "A" )

use this instead:

(!(inPkg.toUpperCase().equals("A")))

NEVER compare strings with == or !=. See: How do I compare strings in Java?

Community
  • 1
  • 1
tckmn
  • 57,719
  • 27
  • 114
  • 156
0

The issue is that you're using == to compare strings. This doesn't do what you think it does (it compares string references, not the character sequences).

Use s1.equals(s2) instead, as in

!inPkg.toUpperCase().equals("A")

etc.

See Java comparison with == of two strings is false?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

== and != compares the Object references. they are not equal as they are not the same object.

String.equals(otherString) compares the content of the String. You want to use this function.

Simulant
  • 19,190
  • 8
  • 63
  • 98