Search⌘ K

Taking Variable Value From User

Explore how to take variable values from users in Java by using the Scanner class. This lesson guides you through importing the class, creating a Scanner object, and using nextLine() to read keyboard input for variables.

Taking user input

We can assign values to variables by means of constants. However, sometimes, we would like the user to input a value for a variable from the keyboard.

See the code given below!

Java
import java.util.Scanner;
class take_input {
public static void main(String[] args) {
Scanner scanner_one = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner_one.nextLine();
System.out.println("Your name is: " + name);
}
}
Did you find this helpful?

Understanding the code

One way to take keyboard input in Java is to use the Scanner class, which is used by first importing the class’ ...