How to take String input in Java
Java nextLine() method
The nextLine() method of Scanner class is used to take a string from the user. It is defined in java.util.Scanner class. The nextLine() method reads the text until the end of the line. After reading the line, it throws the cursor to the next line.
The signature of the method is:
The method returns the line that was skipped. It does not accept any parameter. When it does not find any line, then it throws NoSuchElementException. It also throws IllegalStateException if the scanner is closed.
Example of nextLine() method
Output:
Java next() method
Java next() method can read the input before the space id found. It cannot read two words separated by space. It retains the cursor in the same line after reading the input.
The signature of the method is:
The method returns the next complete token from this scanner. It does not accept any parameter. It throws NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is closed.
Example of next() method
Output:
We can see that whatever we write after Java is skipped by the method and read only the word Java.