VOOZH about

URL: https://www.geeksforgeeks.org/java/scanner-nextline-method-in-java-with-examples/

⇱ Scanner nextLine() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scanner nextLine() method in Java with Examples

Last Updated : 11 Jul, 2025
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present. Syntax:
public String nextLine()
Parameters: The function does not accepts any parameter. Return Value: This method returns the line that was skipped Exceptions: The function throws two exceptions as described below:
  • NoSuchElementException: throws if no line was found
  • IllegalStateException: throws if this scanner is closed
Below programs illustrate the above function: Program 1:
Output:
Gfg 
 Geeks 
 GeeksForGeeks
Program 2: To demonstrate NoSuchElementException
Output:
Exception thrown: java.util.NoSuchElementException: No line found
Program 3: To demonstrate IllegalStateException
Output:
Exception thrown: java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Comment