To take String input in java, we need to use Scanner class in the program. In java Scanner class takes the input by nextLine() method that comes with a Pakage “java.util.Scanner”. nextLine() method scan and reads the text until the end of line then it throughs the cursors to the next line.
If user try to take integer input then users need to declare
The syntex of the nextLine() function is –
public String nextLine();
Code for Taking String Input
Here we wrote a code that shows how Scanner class work with nextLine() method in Java.
// Code for taking String input with nextLine() function.
import java.util.Scanner;
public class mainClass{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.nextLine();
System.out.println("You entered: "+ name);
input.close();
}
}
Output
Enter your name: Dawood You entered: Dawood
In the same way we use nextInt() function to take a Integer type input in Java program.