
Java is a programming language that has been widely used in the software industry for a long time, and it remains popular due to the security it offers for applications built with it.
So far, all the values in our programs have been hardcoded. For example, if a program stores a user's name or age, those values are written directly into the code. While this is useful for learning, real applications need to accept information from users while the program is running.
For example, a banking application asks for an account number, an e-commerce website asks for a delivery address, and a login page asks for a username and password. To make programs interactive, Java provides ways to read input from the user.
In this chapter, you will learn how to accept input from the keyboard using the Scanner class and store the entered values in variables.
User input is any information entered by a user while a program is running.
Examples:
Instead of hardcoding values, we can ask the user to provide them.
Java provides the Scanner class to read input from the keyboard.
Before using Scanner, it must be imported.
import java.util.Scanner;
This gives our program access to the Scanner class.
To read input, create a Scanner object.
Scanner sc = new Scanner(System.in);
Here:
Scanner is the class name.sc is the object name.System.in represents keyboard input.For now, simply remember:
Scanner sc = new Scanner(System.in); is used to read input from the keyboard.Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
}
}
Input:
Rahul
Output:
Enter your name: Rahul Hello Rahul
String name = sc.nextLine();
This line reads a complete line of text entered by the user and stores it in the variable name.
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Your age is " + age);
}
}
Input:
18
Output:
Enter your age: 18 Your age is 18
int age = sc.nextInt();
This line reads an integer value from the keyboard and stores it in the variable age.
Example:
double price = sc.nextDouble();
This reads a decimal number such as:
99.99
and stores it in a double variable.
Wrong:
Scanner sc = new Scanner(System.in);
Without:
import java.util.Scanner;
Java will show an error.
int age = sc.nextInt();
If the user enters:
Rahul
Java will throw an error because nextInt() expects a number.
Scanner class to read input.System.in represents keyboard input.nextLine() reads text.nextInt() reads integers.nextDouble() reads decimal values.