View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Scanner Class in java

Updated on 21/04/20256,217 Views

Let’s say you’re building a program that asks users to enter their name, age, or favorite color. How do you get that input from the keyboard? That’s where the Scanner class in Java comes in handy. It allows you to read input from various sources—like the keyboard, files, or strings—making your programs interactive and user-friendly.

In Java, Scanner is a utility class found in the java.util package. It's commonly used to read input from the console and supports different data types like int, double, String, and more. Scanner helps bridge the gap between user input and your program’s logic, whether you're building a calculator, form-based application, or game.

In this blog, we’ll explore everything you need to know about the Scanner class in Java—its syntax and common methods. Let’s get started!

Combine your Java expertise with professional software engineering skills. Join Upgrad’s Software Engineering course and develop a strong foundation in building high-quality software.

Java Scanner Class Declaration

The "scanner" class in Java reads input from various sources, such as the terminal, files, and strings. To use the Scanner class, first, declare an instance of it.

Learn how to declare a scanner object through this example:

import java.util.Scanner; // Importing the Scanner class to take input from the user
public class ScannerExample {
    public static void main(String[] args) {
        // Creating a Scanner object to read input from the keyboard (System.in)
        Scanner scanner = new Scanner(System.in);

        // Prompting the user to enter an integer
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt(); // Reading an integer input from the user
        System.out.println("You entered: " + num); // Printing the entered integer

        // Prompting the user to enter a line of text
        System.out.print("Enter a line of text: ");
        scanner.nextLine(); // This line is needed to consume the leftover newline character after nextInt()

        String str = scanner.nextLine(); // Reading the actual line of text from the user
        System.out.println("You entered: " + str); // Printing the entered text

        scanner.close(); // Closing the Scanner object to free up resources
    }
}

Output

Enter an integer: 10
You entered: 10
Enter a line of text: Hi, I'm learning scanner class in JAVA!
You entered: Hi, I'm learning scanner class in JAVA!

How to Use Java Scanner?

In Java, you can create a scanner object to read input from various sources. These sources are the console, files, or strings. To specify the source of input, you pass an appropriate input stream or source to the scanner constructor.

For instance, if you want to read input from the console, you can create a scanner object. Then pass the “System.in” input stream to its constructor like this:

Scanner scanner = new Scanner(System.in);

This creates a scanner object named scanner that reads input from the console.

On the other hand, if you want to read input from a string, you can create a scanner object and then pass the string to its constructor like this:

Scanner scanner = new Scanner("Hello, UpGrad!");

This creates a scanner object that parses the string "Hello, UpGrad!" and allows you to read its contents using Scanner methods such as “next(),” “nextInt(),” or “nextLine().”

You can also create a scanner object to read input from a file or any other input stream. In this case, you would pass the file or stream to the scanner constructor instead of “System.in” or a string.

Java Scanner Class Constructors

The scanner class provides several constructors. They allow you to create a scanner object to read input from different sources.

Here are the primary constructors the scanner class provides:

Constructor

Description

Scanner(File source)

Creates a scanner to read input from a file.

Scanner(InputStream source)

Reads input from a byte stream (e.g., System.in).

Scanner(String source)

Reads input from a given string.

Scanner(Readable source)

Reads input from a character stream.

Scanner(Path source)

Reads input from a file specified by a Path object.

Scanner(File source, String charsetName)

Reads input from a file using a specified character encoding.

Scanner(InputStream source, String charsetName)

Reads input from a byte stream using a specific character set.

Scanner(ReadableByteChannel source)

Reads input from a byte channel.

Scanner(ReadableByteChannel source, String charsetName)

Reads input from a byte channel using a specified character set.

Scanner(Path source, String charsetName)

Reads input from a file (via Path) using the specified character encoding.

Take your Java skills to new heights. Enroll in the Executive Diploma in Data Science & AI with IIIT-B and expand your expertise.

Java Scanner Class Methods

Here is a list of scanner class methods in Java

1. close() - Closes the scanner object and frees any associated system resources.

Scanner scanner = new Scanner(System.in);

scanner.close();

2. hasNext() - Returns true if another token is in the input.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
    String input = scanner.next();
    System.out.println("Input: " + input);
}

3. hasNextLine() - Returns true if there is another line in the input.

Scanner scanner = new Scanner("Hello,\nworld!");
if (scanner.hasNextLine()) {
    System.out.println("Found next line: " + scanner.nextLine()); // Output: Found next line: Hello,
}

4. next() - Returns the next token in the input as a string.

Scanner scanner = new Scanner("Hello, world!");
String word = scanner.next();
System.out.println(word); // Output: Hello,

5. useLocale(Locale locale): Sets the scanner's locale to the specified locale.

Scanner scanner = new Scanner("1.234,56");
scanner.useLocale(Locale.GERMAN);
double num = scanner.nextDouble(); // num = 1234.56

6. useRadix(int radix): Sets the scanner's radix to the specified radix.

Scanner scanner = new Scanner("FF");
scanner.useRadix(16);
int num = scanner.nextInt(); // num = 255

7. findAll(Pattern pattern): Returns a stream of match results that match the specified regular expression pattern.

Scanner scanner = new Scanner("Hello, World!");
Pattern pattern = Pattern.compile("\\w+");
scanner.findAll(pattern).forEach(matchResult -> System.out.println(matchResult.group()));
// Output: Hello World

8. nextLine() in Java - Returns the next line of input as a string.

Scanner scanner = new Scanner("Hello,\nworld!");
String line = scanner.nextLine();
System.out.println(line); // Output: Hello,

9. nextDouble() - Returns the next token in the input as a double.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a double value: ");
double input = scanner.nextDouble();
System.out.println("Input value: " + input);

10. nextBoolean() - Returns the next token in the input as a boolean.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a boolean value (true/false): ");
boolean input = scanner.nextBoolean();
System.out.println("Input value: " + input);

11. nextByte() - Returns the next token in the input as a byte.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a byte value: ");
byte input = scanner.nextByte();
System.out.println("Input value: " + input);

12. nextShort() - Returns the next token in the input as a short.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a short value: ");
short num = scanner.nextShort();
System.out.println("The entered short value is " + num);

13. nextLong() - Returns the next token in the input as a long.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a long value: ");
long num = scanner.nextLong();
System.out.println("The entered long value is " + num);

14. nextFloat() - Returns the next token in the input as a float.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a float value: ");
float input = scanner.nextFloat();
System.out.println("Input value: " + input);

15. useDelimiter() - Sets the delimiter for parsing input.

Scanner scanner = new Scanner("Hello,world!");
scanner.useDelimiter(",");
System.out.println(scanner.next()); // Output: Hello
System.out.println(scanner.next()); // Output: world!

16. skip() - Skips input that matches the specified pattern.

Scanner scanner = new Scanner("1,2,3,4,5");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        int num = scanner.nextInt();
        System.out.println(num);
    } else {
        scanner.skip(",");
    }
}

17. findInLine() - Searches for the next occurrence of the specified pattern in the current input line.

Scanner scanner = new Scanner("Hello, 123, world!");
String match = scanner.findInLine("\\d+");
System.out.println(match); // Output: 123
Scanner scanner = new Scanner("The quick brown fox jumps over the lazy dog.");
String result = scanner.findInLine("fox");
System.out.println(result); // Output: fox

18. findWithinHorizon(String pattern, int horizon) - Searches for the next occurrence of the specified pattern in the input up to the specified horizon.

Scanner scanner = new Scanner("abc123def456");
System.out.println(scanner.findWithinHorizon("\\d+", 3));
// Output: null (pattern not found within horizon of 3 characters)

19. hasNextByte(): Returns true if the scanner has another token that is a byte.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextByte()) {
    byte b = scanner.nextByte();
    System.out.println("Byte: " + b);
}

20. match() - Returns the MatchResult for the last match operation.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.next();
scanner.useDelimiter("[aeiou]");
scanner.next();
MatchResult result = scanner.match();
System.out.println("Last match: " + result.group());

21. ioException() - Returns the IOException last thrown by the scanner's underlying Readable.

Scanner scanner = new Scanner(new java.io.FileReader("nonexistent.txt"));
try {
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (java.util.NoSuchElementException e) {
    if (scanner.ioException() == null) {
        System.out.println("Scanner is still valid, but there is no more input");
    } else {
        System.out.println("Scanner is invalid due to an IOException: " + scanner.ioException().getMessage());
    }
}
// Output: Scanner is invalid due to an IOException: null (file not found)

22. delimiter() - Returns the current delimiter pattern as a string.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
    System.out.println("Word: " + scanner.next());
}

23. locale() - Returns the locale associated with the scanner.

Scanner scanner = new Scanner("one deux trois");
scanner.useLocale(Locale.FRENCH);
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}
// Output: one
//         deux
//         trois
System.out.println(scanner.locale());
// Output: fr_FR

24. radix() - Returns the default radix for parsing integers.

Scanner scanner = new Scanner(System.in);
scanner.useRadix(16);
System.out.println("Enter a hexadecimal number: ");
int num = scanner.nextInt();
System.out.println("The entered hexadecimal number is " + num);

25. reset() - Resets the scanner to its initial state.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
    System.out.println("Word: " + scanner.next());
}
scanner.reset();
System.out.println("Original delimiter: " + scanner.delimiter());

26. toString() - Returns a string representation of the scanner object.

Scanner scanner = new Scanner("hello world");
System.out.println(scanner.toString());

27. tokens() - Returns an Iterator over the tokens in the input.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
Iterator<String> tokens = scanner.tokens();
while (tokens.hasNext()) {
    System.out.println("Token: " + tokens.next());
}

28. remove() - Removes the current token from the input.

Scanner scanner = new Scanner("apple orange banana");
while (scanner.hasNext()) {
    String fruit = scanner.next();
    System.out.println(fruit);
    if (fruit.equals("orange")) {
        scanner.remove();
        System.out.println("Removed " + fruit);
    }
}

29. hasNextBigDecimal() - Returns true if there is another token in the input, and it can be interpreted as a BigDecimal.


Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigDecimal()) {
    BigDecimal decimal = scanner.nextBigDecimal();
    System.out.println("Decimal: " + decimal);
}

30. nextBigDecimal() - Returns the next token in the input as a BigDecimal.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigDecimal value: ");
BigDecimal input = scanner.nextBigDecimal();
System.out.println("Input value: " + input);

31. hasNextBigInteger() - Returns true if there is another token in the input, and it can be interpreted as a BigInteger.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigInteger()) {
    BigInteger integer = scanner.nextBigInteger();
    System.out.println("Integer: " + integer);
}

32. nextBigInteger() - Returns the next token in the input as a BigInteger.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigInteger value: ");
BigInteger input = scanner.nextBigInteger();
System.out.println("Input value: " + input);

33. hasNextBoolean() - Returns true if the scanner has another boolean token.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBoolean()) {
    boolean bool = scanner.nextBoolean();
    System.out.println("Boolean: " + bool);
}

34. hasNextPattern() - Returns true if the next token in the input matches the specified pattern.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.next();
if (scanner.hasNextPattern("\\d+")) {
    int num = scanner.nextInt();
    System.out.println("The entered string is: " + str + " and the number is: " + num);
} else {
    System.out.println("The entered string is: " + str);
}

35. nextInt() in Java- Returns the next token in the input as an int.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("The entered integer is " + num);

36. hasNextDouble() - Returns true if there is another token in the input, and it can be interpreted as a double.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextDouble()) {
    double d = scanner.nextDouble();
    System.out.println("Double: " + d);
}

37. hasNextFloat() - Returns true if another token is in the input and can be interpreted as a float.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextFloat()) {
    float f = scanner.nextFloat();
    System.out.println("Float: " + f);
}

38. hasNextInt() - Returns true if there is another token in the input, and it can be interpreted as an int.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
    int i = scanner.nextInt();
    System.out.println("Int: " + i);
}

39. hasNextLong() - Returns true if another token is in the input and can be interpreted as a long.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a long value: ");
if (scanner.hasNextLong()) {
    long value = scanner.nextLong();
    System.out.println("You entered: " + value);
} else {
    System.out.println("Invalid input");
}

Conclusion

The Scanner class in Java simplifies user input by providing easy methods to read data from various sources like keyboard, files, or strings. Its flexibility and built-in parsing capabilities make it ideal for beginners and professionals alike. You can efficiently handle input operations in Java-based applications and programs by understanding its constructors and usage.

FAQs on Scanner Class in Java

1. What is the Scanner class used for in Java?

The Scanner class is used to read input from various sources such as keyboard, files, strings, or byte streams. It provides methods to parse primitive types like int, double, and boolean, making it easier to handle user input or file data.

2. Which package does the Scanner class belong to?

The Scanner class is part of the java.util package. You need to import it using import java.util.Scanner; at the beginning of your program to use it.

3. How do you create a Scanner object to read input from the keyboard?

You can create it using:

Scanner sc = new Scanner(System.in);

This allows the program to read user input from the console.

4. What methods are available in Scanner to read different data types?

Scanner provides methods like nextInt(), nextDouble(), nextBoolean(), nextLine(), next(), and nextFloat() to read specific data types directly from the input source.

5. What is the difference between next() and nextLine() in Scanner?

next() reads input until a space is encountered, while nextLine() reads the entire line, including spaces, until a newline character is found. Use nextLine() when you want to capture full-line input.

6. How to read input from a file using Scanner in Java?

You can use:

Scanner sc = new Scanner(new File("filename.txt"));

This allows you to read file contents line by line or token by token using Scanner methods.

7. What happens if the input type doesn't match the expected Scanner method?

A java.util.InputMismatchException is thrown. For example, if you use nextInt() and enter a string, the program crashes. Always validate input or use hasNextInt() before reading.

8. How can I read an entire line after using nextInt() or next()?

Use an extra nextLine() after methods like nextInt() to consume the leftover newline character in the input buffer before reading the full line.

9. Can Scanner read input from a string or a path?

Yes. You can use:

Scanner sc = new Scanner("Some text");

or

Scanner sc = new Scanner(Paths.get("file.txt"));

to read input from a string or a file path, respectively.

10. Do we need to close the Scanner object in Java?

Yes, especially when reading from files or input streams. Closing the Scanner releases system resources. Use sc.close(); at the end. But avoid closing it if it's tied to System.in to prevent losing console input.

11. Is Scanner class thread-safe?

No, the Scanner class is not thread-safe. If you’re using it in a multi-threaded environment, you should synchronize access or use thread-safe alternatives like BufferedReader with proper locking mechanisms.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.