Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
inputinjava

Scanner class in Java

Adithya Challa

Overview

In Java, we can read the input data from the user with the help of the Scanner class. The Scanner class is part of the java.util package.

Syntax

This is the syntax of the Scanner class:

  • Create an object of the Scanner class by passing System.in as a parameter to its constructor.
  • System.in represents the standard input stream.
Scanner object_name = new Scanner(System.in);

Available methods

We can use the following methods based on the input type:

Input type Method
String nextLine()
Short next short()
Int nextInt()
Double nextDouble()
Byte nextByte()
Float nextFloat()
Long nextLong()
Boolean nextBoolean()
BigInteger nextBigInteger()
BigDecimal nextBigDecimal()

Code example

To execute the code given below, enter input in this format with a single whitespace between each input variable:

Name Age GPA

import java.util.Scanner;

class Main {
  public static void main(String[] args){
    //("Enter name");
    //("Enter Age");
    //("Enter GPA");
    
    // Creating an object of Scanner
    Scanner obj = new Scanner(System.in);
    String name = obj.next();
    int age = obj.nextInt();
    float gpa = obj.nextFloat();

    System.out.println("Name="+name);
    System.out.println("Age="+age);
    System.out.println("GPA="+gpa);
  }
}

Enter the input below

Sample code

Code explanation

  • Line 1: We import the Scanner class, that is, import java.util.Scanner;.
  • Lines 7–9: We enter the details for the Name,Age, and GPA values.
  • Lines 12–15: We create the object of the Scanner class. There is a list of available methods from which we can select a method to use.
  • Lines 17–20: We display the output.

RELATED TAGS

java
communitycreator
inputinjava
RELATED COURSES

View all Courses

Keep Exploring