Difference between next() and nextLine() methods in Java

Hello programmer, in this tutorial you will be going to learn the difference between next() and nextLine() methods in Java. This tutorial differentiates between next() and nextLine() methods with the help of a Java program.

next() method

Explanation with the help of an example:

  • First, you make two variables of type string. Then use the next() method to store value in it.
  • After that, when you run this program.
    The cursor will read the first String till the whitespace (Note next() method cannot read two strings with space separated).
  • After the spacebar is pressed and blank space occurs then if you enter the next string it is stored in a new variable.
    (Note here that the next() method doesn’t shift the cursor to the next line it remains in the same line to continue reading the output).
  • Or if you press the enter key the cursor then only shifts to a new line and reads input again till the white space is encountered.

CODE:

import java.util.*;
public class Next{

  public static void main(String args[]){
  Scanner scan = new Scanner(System.in);
  String a = scan.next();
  String b = scan.next();
  System.out.println(a);
  System.out.println(b);
  

}

}

OUTPUT:

Java Language

Java

Language

nextLine() method

Explanation with the help of an example:

  • First, you make two variables of type string. Then use the nextLine() method to store value in it.
  • After that, when you run this program.
    The cursor will read the input till the end of the line(Note here that in this nextLine() method the space between two strings is read as a complete line and is stored only in one variable).
  • After reading the output from the first line including space between two words. the cursor then shifts to a new line to read input and store it in the second variable. (Note here that after reading the first input the cursor position is changed and it starts to read input from a new line).
  • nextLine() method is helpful when you want to read an entire line.

CODE:

import java.util.*;
public class NextLine{

  public static void main(String args[]){
  Scanner scan = new Scanner(System.in);
  String a = scan.nextLine();
   	String b = scan.nextLine();
  System.out.println(a);
  System.out.println(b);	
  

}

}

OUTPUT:

Java Language

Is More Popular Than Other Languages

Java Language

Is More Popular Than Other Languages

Leave a Reply

Your email address will not be published.