[Java] next(), nextLine()
The scanner class consists next() and nextLin() methods.
next() Method:
The next() method in java is present in the Scanner class and is used to get the input from the user.
In order to use this method, a Scanner object needs to be created. This method can read the input only until a space (" ") is encountered. In other words, it finds and returns the next complete token from the scanner.
Example of next()
Class Main {
public static void main(String[] args) {
//creating the Scanner object
Scanner sc = new Scanner(System.in);
//Use of the next() method
String Input = sc.next();
System.out.println(Input);
}
}
Input
Geeks for
geeks
Output
Geeks
nextLine() Method:
The nextLine() method in java is present in the Scanner class and is used to get the input from the user.
In order to use this method, a Scanner object needs to be created. This method can read the input till the end of line.
In other words, it can take input until the line change or new line and ends input of getting '\n' or press enter.
Example of nextLine()
class Main2 {
public static void main(String[] args) {
//creating the object of the
//Scanner class
Scanner sc = new Scanner(System.in);
//Use of nextLine() method
String Input = sc.nextLine();
System.out.println(Input);
Input
Geeks for
geeks
Output
Geeks for