Difference between next() and nextLine()In Java, the Scanner class available in the java.util.package is one of the easiest ways for obtaining input of the primitive data types such as int, double, and strings. In competitive programming, time is a constraint, and using the Scanner class is not an efficient way for scenarios where time is a constraint. Let's understand both the methods one by one with an example: next() MethodThe next() method of the Scanner class is used for getting input from the user. In order to use the next() method of the Scanner class, an instance of the Scanner class needs to be created. The next() method stops reading input from the user until it receives a white space(" "). So, it returns the next complete token from the Scanner. Let's take an example to understand how the next() method is used for taking input from the user. NextExample.java Output: nextLine() MethodThe nextLine() method of the Scanner class is also used for taking input from the user. In order to use the nextLine() method, we also need to create an instance of the Scanner class. The nextLine() method is capable of reading input till the end of the line. So, it stops reading input from the user when the user presses the enter key or line change. Let's take an example to understand how the nextLine() method is used for taking input from the user. NextLineExample.java Output: Difference between the next() and the nextLine()The given table describe the difference b/w the next() and the nextLine() methods:
Next TopicJava Split String by Comma |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India