Java Scanner Example – Reading Input from Console

The java.util.Scanner class used for scanning text. java.util.Scanner parses primitive types and strings using regular expressions.

Here what you should know about Java Scanner:

  • Scanner breaks the input into tokens using a delimiter pattern, which by default matches white-space.
  • Scanning operation may block waiting for input.
  • Scanner is not thread safe! For multi-threaded environment you’ll need to implement synchronization mechanism.

Let’s see how it works on this simple program:

public static void main(String[] args){

        System.out.println("Enter your name: ");
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();
        System.out.println("Hello " + username);
    }

 
Program output:

Enter your name: 
John
Hello John

Here we simply passing the console input to the Scanner and actually reading the input by scanner.nextLine() command.

Let’s improve our program by asking for user age. This time we’ll use scanner.nextInt() command which automatically convert the input into integer:

public static void main(String[] args){

        System.out.println("Enter your name: ");
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();
        System.out.println("Hello " + username);

        System.out.println("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println( age + "?!! You're a big boy!");
        scanner.close()
    }

 
Program output:

Enter your name: 
John
Hello John
Enter your age: 
35
35?!! You're a big boy!

Notice that in order to prevent memory leaks in your java application you should terminate the scanner after use by scanner.close() command.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.