The difference between next() and nextLine()

·

2 min read

nextLine() will store the complete sentence inputted in the String variable whereas next() will only save the first word inputted and the rest will go in an input buffer.

If you use a next() then a next(),

import java.util.Scanner;
public class test1{
    public static void main(String a[]){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Testing");
        String name1 = scanner.nextLine(); // if input: John Doe Tom
        System.out.println("name1: "+ name1); // output: John Doe Tom  

        String name2 = scanner.next();// if input: John Doe Tom
        System.out.println("name2: "+ name2); // output: John  , the rest will be in the input buffer

        String name3 = scanner.next();// that is the input buffer, it will not let you input anything in it 
        System.out.println("name3: "+ name3); // output: Doe
        scanner.close();
    }
}

It will break the sentence into different words without any place. Tom is still in the buffer.

If you use a next() and then a nextLine(),

import java.util.Scanner;
public class test1{
    public static void main(String a[]){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Testing");
        String name1 = scanner.nextLine(); // if input: John Doe Tom
        System.out.println("name1: "+ name1); // output: John Doe Tom    

        String name2 = scanner.next();// if input: John Doe Tom
        System.out.println("name2: "+ name2); // output: John  , the rest will be in the input buffer

        String name3 = scanner.nextLine();// that is the input buffer, it will not let you input anything in it 
        System.out.println("name3: "+ name3);
        scanner.close();
    }
}

the rest of the sentence will display in name3 with its space in front