dave
dave

Reputation: 419

why is this expression returning true

(pass[i]!= null) && (pass[i].getName()!= "nullnull") <--returning true when I debug it even though the value of pass[i].getName() == "nullnull" when I check it using the Expressions window in eclipse while debugging

im using the input dialog box to input two names

String firstName = (String)JOptionPane.showInputDialog("Enter First Name");
String lastName = (String)JOptionPane.showInputDialog("Enter Last Name");

and returning

public String getName()
    {
        return FirstName + LastName;
    }

Upvotes: 0

Views: 112

Answers (5)

trutheality
trutheality

Reputation: 23455

Strings should not be compared with == or !=. Use String.equals().

== will return true and != will return false only when both Strings are the same string object (which is different from comparing the text they represent).

Upvotes: 1

Bohemian
Bohemian

Reputation: 424963

To be honest, it's almost always going to be true:

In java the == operator comparer object references. you want the .equals() method.

There's a gap in your code - it will explode if getName() returns null.

Upvotes: 0

Sai
Sai

Reputation: 3947

Try using ".equals"

(pass[i]!= null) && !(pass[i].getName().equals("nullnull"))

Upvotes: 4

Bala R
Bala R

Reputation: 108937

I think you need

    (pass[i]!= null) && (!pass[i].getName().equals("nullnull"))

Upvotes: 2

SLaks
SLaks

Reputation: 887195

You have two different strings with the same value, but you're comparing them by reference.

You need to compare them by value by writing "nullnull".equals(pass[i].getName()).
The reversed order will work even if getName() returns null.

Upvotes: 5

Related Questions