0

Here is my problem, the if statement doesn't show the messagedialog when i don't insert anything in the inputdialog, but when i use != to compare the condition, it showup, why is this? as i know != mean not equal and == is equal

    String firstName = "";
    String lastName = "";

    firstName = JOptionPane.showInputDialog("Please enter your first name");

    if (firstName == "") {
        JOptionPane.showMessageDialog(null, "Don't leave it blank!");
    } else
    {
        lastName = JOptionPane.showInputDialog("Please enter your last name");
    }

    String msg = "Hello " + firstName + lastName + "!";
    JOptionPane.showMessageDialog(null, msg);
PotterWare
  • 63
  • 1
  • 1
  • 4
  • Yep, you're right -- Java's obviously broken. Has noting to do with attempting to compare strings with `==`. – Hot Licks May 01 '13 at 03:33

1 Answers1

3

One of the most common mistakes in java. String require a .equals() rather than an ==.

Wrong:

if (str == "foo") {

}

Right:

if ("foo".equals(str)) { // done in this order to avoid NPE

}
nook
  • 2,378
  • 5
  • 34
  • 54