Basic Authentication Program in Java
Check username and password against hardcoded values.
BeginnerModule 2: Conditional ProgramsExample 20 of 20
basic-authentication-program.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 final String USERNAME = "admin";6 final String PASSWORD = "1234";78 Scanner sc = new Scanner(System.in);910 System.out.print("Enter username: ");11 String user = sc.nextLine();12 System.out.print("Enter password: ");13 String pass = sc.nextLine();1415 if (USERNAME.equals(user) && PASSWORD.equals(pass)) {16 System.out.println("Login Successful");17 } else {18 System.out.println("Invalid Credentials");19 }2021 sc.close();22 }23}
Output
Enter username: admin Enter password: 1234 Login Successful
What's going on
Use equals(), not ==. == compares references. Two equal-looking strings from Scanner are still different objects.
Hardcoded admin/1234 is a demo. Do not ship it. Scanner does not hide the password.