Difference Between next() and nextLine() Methods in JavaJava next() MethodThe 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. The 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. next() can read the input only till the space. It cannot read two words separated by a space. Also, next() places the cursor in the same line after reading the input. NextMethod.java Input Output: First Java nextLine() MethodThe nextLine() in Java is a method of the java.util.Scanner class. It reads the input string unless the line changes or a new line and then ends the input with \n or pressing enter. Usually, if we are taking any other type of input like int or String word input with the next() method before the nextLine() method we usually add an extra nextLine() method just before the nextLine() method, otherwise the nextLine() method will return a blank String. Another way would be to always use nextLine() wrapped into an Integer.parseInt(). The method does not accept any parameter. It returns the value in the string it returns the current line that was skipped. Exceptions The nextLine() in Java throws two types of exceptions:
Example of nextLine() MethodIn this following code, we will see how the nextLine() method reads the input string unless the line changes or a new line and then ends the input with \n or pressing enter and keep the next line input as a buffer for the next method. NextLine.java Output: Hello World Hello World Let's see another example. NextLineExample.java Output: Output: The integer value is : 10 String word value is : Hello String next line value is : World Internal Working of nextLine() Method in Java?The nextLine() in Java is a method of the java.util.Scanner class. It is used to store the user input value of the String type. Before implementing this method to obtain the user's input, it is necessary to construct a Scanner object. The main purpose of the method is that it reads the input up till the end of the line. It reads the input string unless the line changes or a new line and then ends the input with \n or pressing enter. Since nextLine() in Java, while looking for a line separator continues to read through the input, it may buffer all of the input reading for the line to ignore if there are no line separators present. nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line. Java next() Vs. nextLine() Method
|