Scanner Next() Method Java

Next method

Now let’s discuss the next() method, with which we can take a complete token as an input from the user. This method returns the next complete token from the Scanner.

Get a complete token as input (next method)

Have a look at the below program which demonstrates the use of the next() method –

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.next();
System.out.println(word);
}
}

So, with the next() method, we can have only one word as user input. This means that if you give some user input like “I am learning Java programming language”, and if you try to print word (the variable in which we have stored the user input), you will get “I” as an output. This is because when it saw the space, it thought that the string has ended, and stored whatever is there before the space. If you want to get the whole line, like if you want to take such inputs from the user which are going to contain spaces, then you can better make use of the next line() method. This helps us take lines of text as user input.