Java next() vs nextLine() differences with examples

Java next() vs nextLine():

Both next() and nextLine() methods are defined in the java.util.Scanner class. The Scanner class is mainly used to read user inputs and both of these methods are used to read user inputs. In this post, we will learn how to use these methods with examples.

Scanner next() method:

The next() method is defined as below:

public String next()

This method returns the user-input value as a string. It returns the next token. Note that this method reads a string until a white space is received.

Let me show you how it works with an example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a string: ");
        String str = sc.next();

        System.out.println("You have entered: " + str);
    }
}

Here,

  • We created a Scanner object sc.
  • It asks the user to enter a string. The returned value of sc.next() is stored in the string variable str.
  • The last println line is printing the value of str.

If you run this program, it will print the user-input value.

Enter a string: 
hello world
You have entered: hello

You can see that the reading stops when it finds a white space. If you want to read a line with white spaces, you need to use the nextLine() method as explained below.

Scanner nextLine() method:

The nextLine method is similar to the next method. It also returns the user-input string.

public String nextLine()

The advantage of nextLine is that it reads the input till a new line character is found. So, if the user enters a line with blank spaces, it will read the line. Let me change the above program to use nextLine:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a string: ");
        String str = sc.nextLine();

        System.out.println("You have entered: " + str);
    }
}

We are using the same variables as the previous example. The only difference is that it uses nextLine instead of next. If we use nextLine, it will read the blank spaces as well.

It will print output as below:

Enter a string: 
hello world
You have entered: hello world

Enter a string: 
Hello World !!
You have entered: Hello World !!

You might also like: