In Java, programs often need to get input from users, whether it is numbers, text, or other data. The Scanner class in Java makes this task easy by allowing developers to read input from the keyboard, files, or even strings. In this blog, we will discuss the Scanner class in Java in detail, along with its examples and methods.
What is the Scanner class in Java?
The Scanner class in Java is a utility class used to read input from the keyboard (System.in), files, strings, and other input streams. It belongs to java.util package provides methods to parse primitive data types and strings in Java using regular expressions.
Before Java 5, reading console input required classes like BufferedReader or InputStreamReader. But, with the introduction of Scanner in Java 5 (JDK 1.5), input handling became much more straightforward and user-friendly.
Scanner class in Java Syntax
Below is the syntax of the Scanner class in Java.
Scanner sc = new Scanner(System.in);
- System.in is the standard input stream (keyboard)
- sc is the reference variable of the Scanner class
Before using the Scanner class, you have to import the package java.util.Scanner;
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
How to Use the Scanner Class in Java?
The following steps can be used to use the Scanner class in Java:
Step 1: Import the Scanner class
Before using the Scanner, you need to tell Java that you want to use it, which is done by importing it at the top of your Java file. You can do this with the import java.util.Scanner;.
Step 2: Create a Scanner object
After importing, you have to create a Scanner object, which will read input from the user. After that, you can create it using Scanner sc = new Scanner(System.in);. Here, System.in means the Scanner will read from the standard input, usually the keyboard.
Step 3: Prompt the user for input
To let the user know what input he has to give to the compiler. This can be done by using a simple System.out.println(“Enter your input: “);. The clear prompt will help the user to understand what kind of data to enter.
Step 4: Read the input
To read the input, use the appropriate Scanner method for the input type you need. For example, use nextLine() for a full line of text, nextInt() for an integer, nextFloat() for a decimal number, or nextBoolean() for a true/false value.
Step 5: Use the input in your program*
Once the input is read, you can use it in calculations, display it, or process it further as per your needs. For example, you can print it using System.out.println(“You entered: ” + input); or use it in logic to make decisions.
Step 6: Close the Scanner (optional)
After you are done taking input, it is recommended to close the Scanner to free system resources. You can do this with sc.close();. Closing the Scanner Class is especially important when dealing with multiple input sources in larger programs.
Working of the Java Scanner Class
The Scanner class in Java is used to read input from the keyboard, files, or strings. It works by breaking the input from the user into small pieces, which are called tokens. These are usually separated by whitespace. When you create a Scanner object with System.in, to read the input from the keyboard. After that, you use different methods like nextInt(), nextLine(), or nextFloat() to read and convert the input into the data type as per the requirement. Scanner also provides methods such as hasNextInt() or hasNextLine(), which are used to check the input type before reading it. Also, you can customize how the Scanner will split the data input using useDelimiter(). And, once the input is complete, you should close the Scanner class using close() to free system resources.
For example, the user enters the input string
50 3.14 true
First, the Scanner object will read the entire line and split it into three tokens: “50”, “3.14”, and “true”. Then, it will read “50” as an integer, “3.14” as a decimal number, and “true” as a boolean value.
Scanner Class Methods in Java
The Scanner class in Java provides different methods to read different types of input from the user. Some of them are given below:
1. String Input: String input is used to read the textual data. If you want to read a single word, you can use this method to input until the next space. If you want to read an entire line, including spaces, there is a method that captures the whole line at once. It is mainly useful when the input is for names, addresses, or sentences.
2. Integer Input: Integer input allows you to read the whole numbers from the user. It is helpful when you need different values like age, quantity, or counts. It converts the typed input into an integer, so that you can use it directly in calculations.
3. Floating-Point Input: Floating-point input is used when the user wants to enter numbers with decimals. There are methods that are used for reading both single-precision and double-precision numbers. It is useful for prices, measurements, or any value that requires fractions.
4. Boolean Input: Boolean input reads only the logical values, i.e., either true or false. This is helpful when the user is asking for a simple yes-or-no question or when you have to store the conditions in the form of true or false.
5. Long and Short Input: Long and short input are used to read larger or smaller integer values. Long numbers are useful for things like phone numbers or ID numbers, while short numbers are used for small numeric data.
6. Byte Input: Byte input allows reading very small integer values within a limited range. This type of input is helpful in low-memory applications or when dealing with binary-level data.
7. Token or Word Input: The Scanner class can also read the words or tokens from the input. It breaks the input into smaller pieces automatically, which is helpful when reading multiple values from a single line or parsing structured text. Additionally, the Scanner allows setting a custom delimiter, which means you can read input that is separated by commas, tabs, or other symbols instead of just spaces.
| Input Type |
Scanner Method |
Example Input |
| String (full line) | nextLine() | Akshat |
| Integer | nextInt() | 24 |
| Float | nextFloat() | 1.75 |
| Boolean | nextBoolean() | true |
| Long | nextLong() | 9876543210 |
| Short | nextShort() | 120 |
| Byte | nextByte() | 100 |
| Token / Word | next() | apple |
Example:
Output:
In the above Java program, the information of a person is taken as input from the user, and then displayed.
Get 100% Hike!
Master Most in Demand Skills Now!
Below are the methods that are used for input validation when using the Scanner Class in Java.
1. hasNextLine(): The hasNextLine() method is used to check if there is another line of input available or not. It is mainly used when reading input line by line to ensure that the program does not try to read beyond what the user has entered. This method helps the user to handle the input safely and avoid exceptions when no more data is available.
2. hasNextInt(): The hasNextInt() method is used to check if the next input entered by the user can be read as an integer. It does not read the input; it only tells you whether the next value is a valid integer or not. It is useful to prevent errors when the user enters something that is not a number. For example, you can use it in a loop to keep asking the user for input a proper integer is entered.
3. useDelimiter(): By default, the Scanner splits the input using the whitespaces (space, tab, newline) as a delimiter. The useDelimiter() method allows you to change it and set a custom delimiter. For example, you can tell the Scanner to split input using a comma, semicolon, or any other character. It is very useful when reading structured data like CSV files.
Java Scanner with BigInteger and BigDecimal
We can use BigInteger and BigDecimal with the Scanner Class in Java when we have to deal with very large integers and decimals.
1. BigInteger is used when you need to work with very large integers that are more than the range of int or long. The Scanner class can read them using the next() or nextLine() methods and then convert the input to a BigInteger.
2. BigDecimal is used when you need precise decimal numbers, such as in financial calculations. Like BigInteger, you read input as a string and convert it to BigDecimal.
Let us see the difference between them.
| Feature |
BigInteger |
BigDecimal |
| Stores | Very large integers | Very precise decimal numbers |
| Fraction | No fractional part | Can have a fractional part |
| Use Case | Large numbers, counting | Financial or precise math |
Example:
Output:
In the above Java program, the input is taken from the user and then displayed in its precise form by using BigInteger() and BigDecimal().
Important Points About Java Scanner
Below are some important points one should follow while using the Scanner class in Java.
- Before using the Scanner class, import it at the beginning of the program. So that it can be used to read the input from the user.
- Choose the valid prompt while taking the input from the user, as it will help the user know what kind of information has to be entered.
- Give the input to the program as per the requirement; otherwise, it will crash or throw an error while executing the program.
- Use the correct method according to the data type, such as nextInt() for integers, nextLine() for text, or nextFloat() for decimals.
- If you want the data to be stored in precise form, use BigInteger and BigDecimal.
- If the data has to be separated with special characters, like commas or semicolons, you can use the useDelimiter() method to split the input correctly.
- Always close the Scanner class with the .close() method to free up the system resources.
Unlock Your Future in Java
Start Your Java Journey Today
Conclusion
From the above article, we learned that the Scanner Class in Java is a fundamental concept for taking input from the user. It is present in java.util package and has many different methods depending on the user’s data type.. It starts by breaking the input into small tokens on the basis of the whitespaces present in it, and then converts the input on the basis of the datatype as per the methods used.
Useful Resources:
Scanner Class in Java – FAQs
Q1. What is the Scanner class in Java?
The Scanner class is a utility in Java that helps programs read input from the user, files, or strings.
Q2. What type of class is the Scanner class?
Scanner is a built-in class in java.util package.
Q3. How to write a Scanner class?
You create a Scanner object in your program using: Scanner sc = new Scanner(System.in);
Q4. What does Scanner next() return?
The next() method returns the next word or token from the input as a String.
Q5. What is the use of a Scanner?
The Scanner is used to take input from the user and make it easy to read and process numbers, text, or other data types in a program.