User Input/Output

Taking input: 

Getting Started: We must import the java.util.Scanner package in order to use the Scanner class.

import java.util.Scanner;

Recently, the Scanner class was imported. To use the Scanner class’s methods, we construct an object of that class.

Scanner sc = new Scanner(

The is passed as a parameter and is used to take input.

Note: Your object can be named anything, there is no specific convention to follow. But we normally name our object sc for easy use and implementation.

An object of the scanner class can be created in four different ways. Let’s look at how to generate scanner objects.

  1. Reading keyboard input:

Scanner sc = new Scanner(

  • Reading String input:

Scanner sc = new Scanner(String str)

  • Reading input stream:

import java.util.Scanner;

  • Reading File input:

Scanner sc = new Scanner(File file)

How does a Scanner class operate then?

The inputs are read by the scanner object, which then tokenizes the string. Whitespaces and newlines are the usual criteria used to split the tokens.






The input above will be separated into the letters “Susan,” “19,” “78.95,” and “O.” Depending on the type of Scanner object produced, the Scanner object will then iterate over each token and read it.

Now that we’ve seen how the Scanner object is made, we can see the various ways it may be made, how it reads input, and how it functions. Let’s examine various approaches to gathering input.

The scanner class’s methods are listed below:

nextLine()Accepts string value
next()Accept string till whitespace
nextInt()Accepts int value
nextFloat()Accepts float value
nextDouble()Accepts double value
nextLong()Accepts long value
nextShort()Accepts short value
nextBoolean()Accepts Boolean value
nextByte()Accepts Byte value


import java.util.Scanner;

public class ScannerExample {
	public static void main(String[] args) {
        Scanner sc = new Scanner(;
        System.out.println("Enter Name, RollNo, Marks, Grade");
        String name = sc.nextLine();		//used to read line
        int RollNo = sc.nextInt();			//used to read int
        double Marks = sc.nextDouble();		//used to read double
        char Grade =;	//used to read till space
        System.out.println("Name: "+name);
        System.out.println("Gender: "+RollNo);
        System.out.println("Marks: "+Marks);
        System.out.println("Grade: "+Grade);


Enter Name, RollNo, Marks, Grade
Name: Mohit
Gender: 19
Marks: 87.25
Grade: A
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.