next vs nextLine in Java
Java programming language is very case sensitive, for the beginners of this language it will take a lot of time to master how the syntax and keywords are being used. For instance, the way to type the keywords such as System not a small letter system, public not a Public as capital letter P. Every keywords have their own explanation, in declaring a data type int, small letter int is used to declare variable and another one NextInt() is capital letter for reading input. So, be aware how you are going to use every keywords and data types.
Now, we are going to compare the next and nextLine in Java by providing sample codes.
import java.util.*;
public class hello
{
static Scanner console = new Scanner (System.in);
public static void main(String [] ags)
{
String fname;
System.out.println("Enter you fullname: ");
fname = console.next();
System.out.println("My fullname is: " + fname);
}
}
Output:
When you notice while trying to input your full name? Only Manny will output because console.next reads only the first word of your input not as whole word as Manny Pacquiao.
Now, we are going to figure out the next output what will be the result. Here is the code.
import java.util.*;
public class hello
{
static Scanner console = new Scanner (System.in);
public static void main(String [] ags)
{
String fname;
System.out.println("Enter you fullname: ");
fname = console.nextLine();
System.out.println("My fullname is: " + fname);
}
}
Output:
So, the fullname Manny Pacquiao was the output as whole because the nextLine reads contains spaces not like as next. The only difference of this two sample code is next and nextLine.