Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using if statement on scanner. I write the correct word but if statement fails

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");
        

        
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading