Java Login Console Example

In this example, we use the Scanner class to read login details from the console and validate it with hardcoded data. You can also use the database to validate a userName and password.

Java Scanner - Login Example

In the below example
  • we read userName and password input from the console
  • valid with hardcoded username and password
  • we display a login success message if a username and password matches otherwise we display an error message.

import java.util.Scanner;

public class Login {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner( {
            System.out.print(" Enter user name => ");
            String userName = scanner.nextLine();

            System.out.print(" Enter password => ");
            String password = scanner.nextLine();

            if ("ramesh".equals(userName) && "password".equals(password)) {
                System.out.println(" User successfully logged-in.. ");
            } else {
                System.out.println(" In valid userName of password ");
 Enter user name => ramesh
 Enter password => password
 User successfully logged-in..