So, I’m trying to make a simple scanner password where you input the password and if written correctly it should print out a message
If you input the correct password the code should print a message. But for some reason when I input the correct password it just commits to the else line. And yes I’ve tried the correct password multiple times even with the quotation marks included even though I doubted that.
import java.util.Scanner;
public class newtest {
public static void main(String[]args ) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter password");
String Pass = "Password123";
String password = myObj.nextLine();
if (password == Pass) {
System.out.println("Correct!! Password is: " + password);
}else
System.out.println("WRONG");
}
}
>Solution :
The equality operator you’re using (==) would only work if you’re comparing Pass == Pass or password == password. The operator compares Objects. Only if they’re the same exact object, it would return true.
The .equals() would compare the values of the two strings. Replacing password == Pass with password.equals(Pass) should give you the intended results you want.
This post sums up the details nicely.