Home » Java Tutorial » What is Java Scanner with Examples

What is Java Scanner with Examples

Java is an object-oriented programming language, which means that for doing any activity within the code you need to create particular objects for that. Talking of the objects, every object belongs to a class in java. So, to make coding less complicated, there are many pre-written classes in java which one can use by just creating an object of it. Java Scanner is one of these pre-defined classes of package java.util, which is used to take inputs in Java mainly of primitive data types like integer, double, string etc.

Java Scanner Class

In java.util package, we have this Scanner class which is one of the easiest ways for taking input in the java programming language, but it is not very efficient to take input using java scanner class. When you are competing in a coding competition which has constraints of time and space,it is not advised to use java scanner.

How to use java scanner class?

Basically, for using any method of a class you just need to create the object of the class and through an object, we can access all the variable and methods of that class. For creating the object of pre-defined classes like here we have java scanner, we need to import that particular class to our code as all the pre-defined classes are not present already, we need to import at the time of its use. And after importing, we need to create an object of the class to use methods for inputs present in that class.

Creating java scanner class object

As java Scanner class is part of the java.util package, we have to write import java.util.Scanner to import scanner class. Once it is imported, we can create an object of the class by “Scanner a = new Scanner(System.in)” so here “a” will act as an object. An object will be able to access all the methods of the class, so there are different methods for different datatype inputs like a.nextInt() for integer, a.nextDouble() for double, a.nextLong() for long. Since this, all the methods are followed by an open-close parenthesis.

As mentioned in the above paragraph, the parameter passed at the time of declaring a Scanner class object is very important, like above we passed “System.in” which will take input from the user at the time of execution of the code. You can directly pass a string which you want to give input.

Example:

import java.util.Scanner;
public class Test
{
    public static void main(String[] args)
    {
        // Declaring the object
        Scanner s = new Scanner(System.in);
       // For taking input at the time of execution we used System.in 
 
        // For string input we can use nextLine() method
        String name = s.nextLine();
 
        // For character input
        char sex = s.next().charAt(0);
 
        // Numerical input
        // nextXXX replace XXX with the suitable datatype
        int age = s.nextInt();
        long mobile = s.nextLong();
        double cpi = s.nextDouble();
 
        // Printing all the input values
        System.out.println("Name: "+name);
        System.out.println("SEX: "+sex);
        System.out.println("Age: "+age);
        System.out.println("Mobile Number: "+mobile);
        System.out.println("CPI: "+cpi);
    }
}

Output:

David
M
21
6565131321
8.5
Name: David
SEX: M
Age: 21
Mobile Number: 6565131321
CPI: 8.5

Above example shows various methods in Scanner class java for different types of input types. Here you might be wondering about the way these methods are used with a dot. It is known as dot operator, so here first we created an object of java Scanner class named “s”. Now as we know that using the object of the class we can use any methods or variables of the class, so for that, we write objectname.methodname or objectname.variablename.

Whenever we use java Scanner to take input, we must store that input into a variable, so as shown in the above example age is stored in a variable named age of datatype integer. It is very important to keep the datatype of the variable where we store the input to be the same as the type of data we are going to take as input.

At last, printing all the values will ensure that the input given was stored properly into the memory.

Here is another example for taking input using scanner class java inside a loop to obtain the sum of five numbers given by the user at the time of execution.

Example:

import java.util.Scanner;
public class Test
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
 
int sum = 0, count = 0;
        while (count<5)
        {
            // interger input
            int num = sc.nextInt();
            sum += num;
            count++;
        }
        System.out.println("Sum: " + sum);
    } }

Output:

2
4
5
3
2
Sum: 16

So, we can use java Scanner class this way also where the input statement is inside a loop so that we can have multiple inputs. But here the con for this is that we are storing each input inside the same variable “num” so every time a new input is given, the value inside it gets over-written. But we updated the sum value each time so our problem is solved here but it might not be the case in some other problem. So, we should use this according to the problem statement.

When does an error occur while using Java Scanner Class?

It is very important to take care about the datatype, because as there are different methods for different datatype input in java scanner class, so it is very important to use the appropriate method according to the type of input we provide. If any other datatype value is given as input, then you will get “InputMismatchException”. It would be more clear with the help of an example.

Example

import java.util.Scanner;
public class MyClass {
  public static void main(String[] args) {
	Scanner myObj = new Scanner(System.in);
	System.out.println("Enter name :");
	String name = myObj.nextLine();
	System.out.println("Enter age :");
	int age = myObj.nextInt();
	System.out.println("Enter Salary :");
	double salary = myObj.nextDouble();
 
	// print all the inputs taken
	System.out.println("Name: " + name);
	System.out.println("Age: " + age);
	System.out.println("Salary: " + salary);
  }
}

Output:

Enter name :David
Enter age :30
Enter Salary :30000
Name: David
Age: 30
Salary: 30000.0

In this example, if we provide any numerical value at the time of entering name, then we will get an exception. Also, if in salary input instead of 30000 we give input as 30k then also it might give an exception because it is not a pure numeric value. So it is very important to add proper statements about what exact input is required to avoid exceptions.

Do you know?
1. Java Scanner with Examples
2. Java Stack with Examples
3. ParseInt Java
4. Try Catch JAVA
5. For loop Java with Examples
6. Java vs Javascript
7. Java Iterator with Examples

Pin It on Pinterest