Home »
Java programming language
Different ways to take input from the user in Java
In this tutorial, we will learn about the different ways to take input from the user in Java with the help of examples.
By Preeti Jain Last updated : January 02, 2024
Here is the some of the popular ways to take input from the user in Java,
- By Using BufferedReader Class
- By Using Console Class
- By Using Scanner Class
1. User Input Using BufferedReader Class
Use the readLine() method of the BufferedReader class. BufferedReader object reads input from the standard input stream and is wrapped in BufferedReader.
Example of user input using BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
// Create an object of BufferedReader rdr
BufferedReader rdr =
new BufferedReader(new InputStreamReader(System.in));
// Display message for user
System.out.print("Enter your Job: ");
// BufferedReader object rdr read input from standard input stream
// and wrapped in BufferedReader
String job = rdr.readLine();
System.out.println("You are a " + job);
}
}
Output
Enter your Job: Technical writer
You are a Technical writer
2. User Input Using Console Class
You can use the System.console().readLine() method which is used to read a line from the console in Java.
Example of user input using Console class
public class Main {
public static void main(String[] args) {
// Display message for user
System.out.print("Enter your Job: ");
// Using Console class to take input from user
String job = System.console().readLine();
System.out.println("You are a " + job);
}
}
Output
Enter your Job: Technical writer
You are a Technical writer
3. User Input Using Scanner Class
There are multiple methods of Scanner class that can be used for taking input from the user like next(), nextLine(), nextInt(), nextFloat(), etc.
Example of user input using Scanner class
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
// Display message for user
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.println("My name is " + name);
// Display message for user
System.out.print("Enter your MCA percent: ");
float per = input.nextFloat();
System.out.println("My percent in MCA is: " + per);
}
}
Output
Enter your MCA percent: 98
My percent in MCA is: 98.0