-2
import javax.swing.JOptionPane;
 
public class New {
    public static void main (String[] args) {

        String name = JOptionPane.showInputDialog("Enter your name... ");
        JOptionPane.showMessageDialog(null, "Hi, "+name);

        int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age... "));

        if(age>=18) { JOptionPane.showMessageDialog(null, "Welcome!");}
        else { JOptionPane.showMessageDialog(null, "You are not an adult!");
        System.exit(0);}

        String day = JOptionPane.showInputDialog("What's the day? ");
        if(day == "Monday") { JOptionPane.showMessageDialog(null, "Welcome back to school!");}
        else {JOptionPane.showMessageDialog(null, "Come back later!");}

    }

}

It always gives a "Come back later" message and totally ignoring the "if" -I'm a very beginner, this code is from a tutorial on youtube, tried to edit and I faced this problem-

Progman
  • 16,827
  • 6
  • 33
  • 48
O.M.A.R
  • 9
  • 2
  • In java you cannot compare two strings with `==` you should use `str.equals()` to check for the equality. The condition `day == "Monday"` always returns true. hence, your program is not going to the else statement. – iwrestledthebeartwice Aug 14 '21 at 07:16

2 Answers2

1

The == operator doesn't check whether the values are equal in a String, it does the reference comparison (address comparison)

use:

if(day.equals("Monday"))
devReddit
  • 2,696
  • 1
  • 5
  • 20
1

This is the classic mistake of trying to compare Strings in java with ==. You need to use .equals() so do if(day.equals("Monday"))

https://www.javatpoint.com/string-comparison-in-java

BitNinja
  • 1,477
  • 1
  • 19
  • 25