Introduction

Taking user input and displaying the correct output are two extremely important aspects of any programming language. A programming language is incomplete without these two basic functionalities. Similarly, Java, as a programming language, also has functionalities that make Java programs take input and display the output. The output gets printed on the console using System.out.print() and System.out.println() functions. The input part is handled by the Scanner class. In this article, you will learn in detail about the input functionality of the Java language using Scanner in Java. Also, you’ll learn in detail about how to import Scanner in Java and about the different Scanner class methods in Java.

In this article, we cover:

  1. What is Scanner Class in Java?
  2. How to Use Scanner in Java?
  3. Scanner Object Creation in Java and Their Usage
  4. Java Scanner Class Constructor
  5. Java Scanner Class Methods
  6. Scanner Class Example In Java
  7. Scanner Delimiters
  8. Drawbacks of Scanner Class

1) What is Scanner Class in Java?

Java.util is a package in Java that has a class called Scanner. This class is used to obtain input from the user during runtime. The Scanner input in Java should be of primitive data types, such as int, float, double, etc., and string types. As an example, to get the value of a variable declared as int type, the function used is nextint(). Similarly, for float type input, the function is nextfloat().

For Java Scanner string type and char type inputs, the functions used are nextLine() and next()charAt(0). Here, the next() function gives the next word, and charAt(0) gives the first character in the string. The scanner offers the easiest method to read the input; however, it is not the most efficient one in some cases.

As the Scanner is a class and we create objects for the class to use its methods, so is the case with the Scanner class using Scanner class methods in Java. But for the Scanner class, the predefined object is System.in. The object – System.in denotes the standard input stream in Java.

2) How to Use Scanner in Java?

To use any class in Java, the respective package needs to be imported. Similar is the case with the Java Scanner class. The package of the Scanner class – java.util.Scanner, needs to be imported to use the Scanner class. Given below is the class Scanner in Java syntax to import the package:

import java.util.Scanner;

The above import Scanner Java statement needs to be present in the code before we use the Scanner class.

3) Scanner Object Creation in Java and Their Usage

Once the import of the package is done, the next step is to create the object of the Scanner class. Steps to create the Scanner objects are as follow:

Object to read from file

Scanner obj1 = new Scanner(File filename);

Object to read from the input stream

Scanner obj2 = new Scanner(inputStream inputStreamName);

Object to read input as String

Scanner obj3 = new Scanner(String s);

Refer to the below table to check the commonly used Scanner functions that help take input from the user along with its specific data type.

MethodData TypeDescription
nextInt()IntIt takes int type input value from the user.
nextFloat()FloatIt takes a float type input value from the user.
nextBoolean()BooleanIt takes a boolean type input value from the user.
nextLine()StringIt takes a line as an input value from the user.
next()StringIt takes a word as an input value from the user.
nextByte()ByteIt takes a byte type of input value from the user.
nextDouble()DoubleIt takes a double type input value from the user.
nextShort()ShortIt takes a short type input value from the user.
nextLong()LongIt takes a long type of input value from the user.

4) Java Scanner Class Constructor

Scanner constructor in Java can take any object as input. The input can include the file object too, which lets the Java program take input from a file. Another such object for the Java Scanner class constructor is the inputStream.

The below table describes the Java Scanner class constructors. In this table, you will know how to take string input in Java using Scanner.

ConstructorDescription
Scanner(File FileSourceName)Scanner constructor that creates values scanned from the FileSourceName.
Scanner(File FileSourceName, String charset)Scanner constructor that creates values scanned from the FileSourceName.
Scanner(inputStream inputStreamSource)Scanner constructor that creates values scanned from the inputStreamSource passed.
Scanner(inputStream inputStreamSource, String charset)Scanner constructor that creates values scanned from the inputStreamSource passed.
Scanner(Readable ReadableSource)Scanner constructor that creates values scanned from the ReadableSource specified in the parameter.
Scanner(String StringSource)Scanner constructor that creates values scanned from the ReadableSource specified in the parameter.
Scanner(ReadableByteChannel ChannelSource)Scanner constructor that creates values scanned from the ChannelSource specified in the parameter.
Scanner(ReadableByteChannel Channelsource, String charset)Scanner constructor that creates values scanned from the ChannelSource specified in the parameter.
Scanner(Path PathSource)Scanner constructor that creates values scanned from the PathSource mentioned.
Scanner(Path PathSource, String charset)Scanner constructor that creates values scanned from the PathSource mentioned.

5) Java Scanner Class Methods

The below table contains the Scanner function in Java present under the Java Scanner class. A few functions in the table have two types of Scanner input in Java.

MethodScanner in Java SyntaxDescription
close()Scanner.close()This Scanner method in Java closes the scanner.
delimiter()Scanner.delimiter()This method gets the pattern that the Scanner class uses for delimiter matching.
findInLine()Scanner.findInLine(String pattern) 
Scanner.findInLine(Pattern pattern)
It finds the next occurrence of patterns in the string without considering the delimiters.
It finds the next occurrence of the pattern without considering the delimiters.
findWithinHorizon()Scanner.findWithinHorizon(Pattern pattern, int horizon)

Scanner.findWithinHorizon(String pattern, int horizon)
It finds the next occurrence of a specified pattern, and search occurs till the specified delimiter.
It finds the next occurrence of the specified pattern in the string, and search occurs till the specified delimiter.
hasNext()Scanner.hasNext() 

Scanner.hasNext(String pattern) 
Scanner.hasNext(Pattern pattern)
This Scanner method in Java returns a Boolean value True if there is another input token.
This returns a Boolean value True if the token matches the specified pattern in a String. This returns a Boolean value True if the token matches the specified pattern.
hasNextBigDecimal()Scanner.hasNextBigDecimal()It returns True, if the input is interpreted as Big decimal, else returns False.
hasNextBigInteger()Scanner. hasNextBigInteger()  Scanner. hasNextBigInteger(int radix)It returns True, if the input is interpreted as Big integer, else returns False.

It returns True, if the input in radix is interpreted as Big integer, else returns False.
hasNextBoolean()Scanner.hasNextBoolean()It returns a Boolean value based on the value of the next token.
hasNextByte()Scanner.hasNextByte() 

Scanner.hasNextByte(int radix)
It returns a Boolean value True if the Scanner input is interpreted as Byte, and False if not.
It returns a Boolean value True if Scanner input is interpreted as Byte, and False if not.
hasNextDouble()Scanner.hasNextDouble()It returns a Boolean value True, if the next token value is of double type, else returns False.
hasNextFloat()Scanner.hasNextFloat()It returns a Boolean value True, if the next token value is float type, and false otherwise.
hasNextInt()Scanner.hasNextInt()   Scanner.hasNextInt(int radix)It returns a Boolean value True, if the next token gets interpreted as an integer, else returns false.
It returns a Boolean value True, if the next token gets interpreted as an integer using the radix, else returns false.
hasNextLine()Scanner.hasNextLine()It returns a Boolean value True if there is another input line, and False if no more input.
hasNextLong()Scanner.hasNextLong()   Scanner.hasNextLong(int radix)It returns a Boolean value True if the next input gets interpreted as long, otherwise, it returns False.
It returns a Boolean value True, if the next input using specified radix gets interpreted as long, otherwise, returns False.
hasNextShort()Scanner.hasNextShort() 

Scanner.hasNextShort(int radix)
It returns a Boolean value True if the next input gets interpreted as a short type; otherwise, returns False.
It returns a Boolean value True if the next input, using radix, gets interpreted as a short type; otherwise, returns False.
ioException()Scanner.ioException()This method returns the value of the exception that readable throws last.
locale()Scanner.locale()This method returns the locale.
match()Scanner.match()This Scanner method in Java gives the result of the last match.
next()Scanner.next()This method returns the next token in case it gets matched with the pattern specified.
nextBigDecimal()Scanner.nextBigDecimal()This method returns the BigDecimal value.
nextBigInteger()Scanner.nextBigInteger() 
Scanner.nextBigInteger(int radix)
This method takes the next input as a big integer.
This method takes the next input as a big integer in the radix passed as a parameter.
nextBoolean()Scanner.nextBoolean()This method returns a Boolean value from output.
nextByte()Scanner.nextByte() 
Scanner.nextByte(int radix)
This method takes the next input token as a byte.
This method takes the next input token as a byte from the radix specified.
nextDouble()Scanner.nextDouble()This method takes the next input as a double type.
nextFloat()Scanner.nextFloat()This method takes the next input as a float type.
nextInt()Scanner.nextInt() 
Scanner.nextInt(int radix)
This method scans the next input as int type.
This method scans the next input as the int type in the radix passed in parameter.
nextLine()Scanner.nextLine()This method takes the next input as a String type.
nextLong()Scanner.nextLong() 
Scanner.nextLong(int radix)
This method scans the next input as a Long type.
This method scans the next input value as Long type in the radix specified.
nextShort()Scanner.nextShort() 
Scanner.nextShort(int radix)
This method scans the next input as a short type.
This method scans the next user input as a short type in the radix specified.
radix()Scanner.radix()This method takes the default radix as the next input.
remove()Scanner.remove()This Scanner method in Java removes the Scanner content and gets used when the iterator does not implement the remove operation.
reset()Scanner.reset()This method resets the content of the scanner.
skip()Scanner.skip(Pattern pattern)  Scanner.skip(String pattern)This method skips the input and has to match with the pattern passed in the argument.
This method skips the input having matches with the pattern in the specified string.
toString()Scanner.toString()This method returns the String type of the Scanner input.
useDelimiter()Scanner.useDelimiter(Pattern pattern)
Scanner.useDelimiter(String pattern)
This method sets the pattern as a delimiter.
useLocale()Scanner.useLocale(Locale locale)This method changes the current locale value to the locale value specified.
useRadix()Scanner.useRadix(int radix)This Scanner method in Java changes the current radix value to the radix value specified.

6) Scanner Class Example In Java

Java Scanner Example 1

Read the Scanner program in Java that asks the user to enter the name using the Scanner method in Java nextLine(). Below is the example code:

import java.util.*;

public class Scanner_Example1 {

public static void main(String args[]) {

         Scanner inp = new Scanner(System.in);

         System.out.print(“Please input your name: ”);

         String custName = inp.nextLine();

         System.out.print(“Customer name is “ + custName)

         inp.close();

         }

}

Output:

Please input your name: Peter Soni

Customer name is Peter Soni

Java Scanner Example 2

import java.util.*;

public class Scanner_Example2 {

public static void main(String args[]) {

String str = “Scanner Example”;

Scanner sc = new Scanner(str);

System.outprintln(“String is “ + sc.nextLine());

sc.close();

System.out.println(“Enter Employee Details”);

Scanner inp = new Scanner(System.in);

System.out.print(“Enter employee name: ”);

String empName = inp.next();

System.out.print(“Enter age: ”);

int age = inp.nextInt();

System.out.print(“Enter salary: ”);

double sal = inp.nextDouble();

System.out.println(“Employee Details”);

System.out.print(“Employee name is: ” + empName);

System.out.println(“Employee age: “ + age);

System.out.println(“Employee salary: “ + sal);

inp.close();

}

}

Output:

String is Scanner Example

Enter Employee Details

Enter employee name: Peter John

Enter age: 34

Enter salary: 75000

Employee Details

Employee name: Peter John

Employee age: 34

Employee salary: 75000.00

Java Scanner Example 3

Below code snippet asks user to enter two numbers and returns the sum:

import java.util.Scanner;

class Scanner_Example3 {

public static void main(String[] args) {

Scanner inp = new Scanner(System.in);

System.out.println(“Enter first number: “);

int num1 = inp.nextInt();

System.out.println(“Enter second number: “);

int num2 = inp.nextInt();

inp.close();

int sum = num1 + num2;

System.out.println(“Sum of numbers is “ + sum);

}

}

Output:

Enter first number: 25

Enter second number: 20

Sum of numbers is 45

7) Scanner Delimiters

Scanner class can also be used to split the input tokens. The default delimiter is whitespace, but users can specify the delimiter of their choice while writing the Java code.

Below is the Java code snippet for Scanner delimiter usage:

import java.util.*;

public class ScannerDelimiterExample {

public static void main(String[] args) {

Scanner sc = new Scanner(“10, 12, 14, 16, 18, 20”);

sc.useDelimiter(“\\s*, \\s*);

while(sc.hasNext()) {

                 System.out.println(sc.nextInt());

         }

}

}

Output:

10

12

14

16

18

20

8) Drawbacks of Scanner Class

Although, Scanner class is very useful to take the user input at run time, there are some drawbacks of using Scanner class in Java. Refer to the below shortcomings of using Scanner in Java:

  • When any nextXXX() method gets used after the nextLine() method, the input entered during the execution of nextLine() method gets ignored. This is because the values entered with nextLine() get ignored by the console, and that step gets ignored.
  • Java Scanner is not synchronized.
  • The buffer memory is small in the case of the Java Scanner class.
  • The Scanner class in Java is slow, as the input data gets parsed in the Scanner class.

Conclusion

This was all about the Java Scanner class. All the details about Scanner class in Java, such as the syntax with examples, different Scanner methods, Java Scanner constructor, and drawbacks of the Java Scanner class. You can read similar Java-based articles on Jigsaw Academy and enhance your Java knowledge. You can also check out Jigsaw’s Master Certificate in Full Stack Development if you want to learn Java in more detail.

Also Read

SHARE