Eddie Eddie - 2 months ago 13
Java Question

Issue with Java program validating Username

My Java program isn't working!
Here is my code:

import javax.swing.JOptionPane;
public class practice
{
public static void main(String[] args)
{
String userName = "Eddie"; //username is Eddie
String passWord = "hI"; // passsword is hI
String name;
name = JOptionPane.showInputDialog("Whats your username? ");

if (name == userName)
JOptionPane.showMessageDialog(null, "Exepted!");
System.exit(0);


}
}


Its supposed to ask for my username, and if I type "Eddie" it has to show message dialog "Accepted".But after I type "Eddie" the program closes instead!
Any suggestions?

Answer Source

if (name == userName) should be changed to if (name.equals(userName))

Both equals() and "==" operator in Java is used to compare objects to check equality but main difference between equals method and == operator is that former is method and later is operator.

Read more here to identify the differences: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz44dFcXkwr