User Input in Java

Before moving forward it is very important to know how to take user input in java? At school and college-level without taking user input is ok but when it comes to project-level java user input is necessary.

How to take User Input in Java?

There are several ways to get user input in java. The Scanner class is used to take user input, and this scanner class is present in the java.util package. For using the object of Scanner, we have to import java.util.Scanner package. like: import java.util.Scanner;

Then, we have to create an object of the Scanner class for taking input from the user.

// creating an object of Scanner
Scanner input = new Scanner(;

// taking input from the user
int number = input.nextInt();

Example of taking user input in java:

import java.util.Scanner;

class Input {
    public static void main(String[] args) {
        Scanner input = new Scanner(;
        System.out.print("Enter an integer: ");
        int numb = input.nextInt();
        System.out.println("You entered " + numb);
} else{
    System.out.println("You entered " + numb +" invalid number.");
        // closing the scanner object


user input in java

If you missed our if-else article then please visit once for better understanding of above mentioned example:

User Input Type

we used the nextInt() method, which is used to read integer. To read other java types, we have apply below mentioned method which is described in below table:

nextBoolean()To reads a boolean value from the user.
nextByte()To read a byte value from the user.
nextDouble()To read a double value from the user.
nextFloat()To reads a float value from the user.
nextInt()To reads a int value from the user.
nextLine()To reads a String value from the user.
nextLong()To reads a long value from the user.
nextShort()To reads a short value from the user.

Java Output:

In java we can simply use:

System.out.println(); or

System.out.print(); or


these commands to print an output on screen. Here, System is a class, out is a public static field: it accepts output data.

What is the difference between println, print, printf ?

  • print: It prints strings inside the quotes or values in one row.
  • println: It prints is whatever you provide arguments in string datatype and in unformatted form. And move the cursor to the next line.
  • printf: It prints string formatting (similar to the printf in C/C++ programming).

7 thoughts on “User Input in Java

Leave a Reply

Your email address will not be published. Required fields are marked *