Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java User Input

Java User Input

The Scanner class, found in the java.util package, facilitates obtaining user input in Java.

Utilize the Scanner class by instantiating an object of the class and employing any of its methods as detailed in the Scanner class documentation. For instance, in our example, we will utilize the nextLine() method, designed for reading Strings.

Example

 import java.util.Scanner;  // Import the Scanner class
 class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter username");
     String userName = myObj.nextLine();  // Read user input
    System.out.println("Username is: " + userName);  // Output user input
  }
}
If you are unfamiliar with what a package is, please refer to our Java Packages Tutorial.

Input Types

In the aforementioned example, we utilized the nextLine() method specifically tailored for reading Strings. For reading other data types, refer to the table provided below.

Method

Description

nextBoolean()

Obtains a boolean value from the user.

nextByte()

Obtains a byte value from the user.

nextDouble()

Obtains a double value from the user.

nextFloat()

Obtains a float value from the user.

nextInt()

Obtains an int value from the user

nextLine()

Obtains a String value from the user.

nextLong()

Obtains a long value from the user.

nextShort()

Obtains a short value from the user.

In the following example, we employ various methods to read data of different types:

Example

 import java.util.Scanner;
 class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
     System.out.println("Enter name, age and salary:");
     // String input
    String name = myObj.nextLine();
     // Numerical input
    int age = myObj.nextInt();
    double salary = myObj.nextDouble();
    // Output input by user
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);
  }
}

Note: Providing incorrect input, such as text in a numerical input field, will result in an exception or error message, such as “InputMismatchException.”

For further information on exceptions and error handling, you can explore the Exceptions chapter.