DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java OOPTopic 58 of 59
←PreviousPrevNextNext→

Java User Input

Introduction to User Input

Java provides multiple ways to capture input from users, with the Scanner class being the most common for console-based applications.

Other options include BufferedReader for efficient text input, the Console class for secure password entry, and JOptionPane for graphical dialog input. Handling user input is essential for building interactive programs.

Scanner Class Basics

The Scanner class (from the java.util package) offers convenient methods to read different types of input such as strings, integers, and doubles from the console.

Example
import java.util.Scanner;

public class ScannerBasicExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        System.out.print("Enter your height (in meters): ");
        double height = scanner.nextDouble();
        
        System.out.println("\nHello " + name + "!");
        System.out.println("You are " + age + " years old");
        System.out.println("Your height is " + height + " meters");
        
        scanner.close();
    }
}
Output
Enter your name: John Doe
Enter your age: 25
Enter your height (in meters): 1.75

Hello John Doe!
You are 25 years old
Your height is 1.75 meters

Scanner Methods

MethodDescriptionExample Input
next()Reads a single word (ignores spaces)"Hello World" → "Hello"
nextLine()Reads an entire line including spaces"Hello World" → "Hello World"
nextInt()Reads an integer"25" → 25
nextDouble()Reads a double"3.14" → 3.14
nextBoolean()Reads a boolean"true" → true
hasNext()Checks if more input is availableReturns true/false

Handling Input Validation

Validating input ensures that the program handles unexpected values gracefully and avoids runtime errors like InputMismatchException.

Example
import java.util.Scanner;

public class InputValidationExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age = 0;
        boolean validInput = false;
        
        while (!validInput) {
            System.out.print("Enter your age: ");
            
            if (scanner.hasNextInt()) {
                age = scanner.nextInt();
                if (age > 0 && age < 120) {
                    validInput = true;
                } else {
                    System.out.println("Please enter a valid age (1-119).");
                }
            } else {
                System.out.println("Invalid input! Please enter a number.");
                scanner.next(); // Clear invalid token
            }
        }
        
        System.out.println("Your age is: " + age);
        scanner.close();
    }
}
Output
Enter your age: abc
Invalid input! Please enter a number.
Enter your age: 150
Please enter a valid age (1-119).
Enter your age: 25
Your age is: 25

BufferedReader Alternative

BufferedReader provides efficient reading of text input, especially when reading large inputs line by line. Unlike Scanner, it always reads data as strings, so parsing is required.

Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderExample {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        try {
            System.out.print("Enter your name: ");
            String name = reader.readLine();
            
            System.out.print("Enter your age: ");
            int age = Integer.parseInt(reader.readLine());
            
            System.out.println("Hello " + name + ", you are " + age + " years old");
        } catch (IOException e) {
            System.out.println("Error reading input: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format.");
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                System.out.println("Error closing reader: " + e.getMessage());
            }
        }
    }
}
Output
Enter your name: Jane Smith
Enter your age: 30
Hello Jane Smith, you are 30 years old

Console Class

The Console class allows secure input of sensitive information such as passwords, as characters are not displayed while typing.

Example
import java.io.Console;

public class ConsoleExample {
    public static void main(String[] args) {
        Console console = System.console();
        
        if (console == null) {
            System.out.println("Console not available");
            return;
        }
        
        String username = console.readLine("Enter username: ");
        char[] password = console.readPassword("Enter password: ");
        
        System.out.println("Username: " + username);
        System.out.println("Password length: " + password.length);
        
        java.util.Arrays.fill(password, ' '); // Clear password
    }
}
Output
Enter username: john_doe
Enter password:
Username: john_doe
Password length: 8

Best Practices

- Always validate user input to prevent runtime errors and improve reliability

- Use try-with-resources for automatic closing of Scanner or BufferedReader

- Prefer Console for sensitive input such as passwords

- Release input resources after use to prevent memory leaks

- Give clear prompts and helpful error messages

- Handle number format exceptions when converting string input to numbers

Test your knowledge: Java User Input
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java OOPTopic 58 of 59
←PreviousPrevNextNext→