Home »
Java programming language
Java next() and nextLine() Methods (With Examples)
Java next() and nextLine() Methods: In this tutorial, we will learn about the next() and nextLine() methods of the Scanner class with the help of examples. methods in Java.
By Preeti Jain Last updated : January 02, 2024
Java next() Method
The next() is a method of Scanner class in Java which is used to read input till the space (i.e., it will print string till the space, and whenever it receives a space, it stops working and returns the input before the space). With the help of the next() method, we can't read a string containing spaces.
Syntax
public String next();
public String next(Pattern patt);
public String next(String patt);
Example 1: Input with spaces
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you Skills");
String skills = sc.next();
System.out.println("your skills are " + skills);
}
}
Output
The output of the above example is:
Enter you Skills
c c++ java
your skills are c
Example 2: Input without spaces
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you First Name");
String fn = sc.next();
System.out.println("your First Name is " + fn);
}
}
Output
The output of the above example is:
Enter you First Name
Preeti
your First Name is Preeti
Java nextLine() Method
The nextLine() is a method of Scanner class in Java that is used to take input till the line change. It is commonly used to read a line of text from the standard input (keyboard). With the help of the nextLine() method, we can also read the strings containing spaces.
Syntax
public String nextLine();
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
String name = sc.nextLine();
System.out.println("your name is " + name);
}
}
Output
The output of the above example is:
D:\Java Articles>java NextLine
Enter your name
Preeti Jain
your name is Preeti Jain
Difference Between Java next() and nextLine() Methods
The next() and nextLine() are the methods of the Scanner class and these are used to take user input. The main difference between the next() and nextLine() methods is that the next() method reads a next token (a string without containing spaces) and does not include a new line to the result. While the nextLine() method reads a line (a string containing spaces) and includes a newline to the result.