Due to its platform independence and the multiple other features it offers, it is the first choice for people who want to learn programming. However, taking user input is an important task in Java. Let us learn how to take input from users in Java.
What is the Java language?
Java is an object-oriented programming language used for coding different web applications. It is one of the first choices among developers around the world. It provides multiple features and technologies to make programming effective and fun.
If you are a beginner who wants to learn programming, you must learn how to take input from the user in Java. Let us learn it in this article below.
Write your First Program in Java
Before learning to take input from users, you must be well aware of the fundamentals of Java. Such as printing “hello world” in Java. Learn how to write “Hello World.” However, check out a sample Hello World program in the table below.
Java Hello World Program |
public class HelloWorld { // class name “Hello World”
public static void main(String[] args) { // Main method System.out.println(“Hello, World!”); // Line to print the “Hello World on the output screen.// } } |
Code online on PW Labs: Best Platform to Build, Code, and Deploy
It is important to have a good compiler for executing and debugging your code effectively. PW Skills provides a free online compiler to make coding easier and more interesting. Use various compiler features for free by only signing in using your Google Account.
The PW lab provides cloud storage to save your last work so that you can continue where you left off. Learning programming requires a lot of practice, and here at PW Lab, you can easily code in any language, such as C++, Java, PHP, Python, or any language of your choice. You can also choose compilers and tools based on the type of project, such as data analysis, data science, machine learning, etc.
Also Read: Architecture Of Spring Boot – Examples, Patterns, Diagram
How to Take Input from user in Java: Using Scanner Class
We can easily take input from users in Java using the scanner class. It is a higher version of bufferedReader. The scanner class can read user input and save it in a Java variable.
- In the scanner class, there are no exception errors, so it is easier to implement.
- You can read any data type from the user by using the scanner class.
- The syntax for the scanner class is Scanner sc = new Scanner (System.in).
- You can easily import the scanner class from the util package.
- Use inbuilt scanner functions such as nextInt(), nextFloat(), etc to take different data types.
How to take input from user in Java: using Scanner class |
import java.util.Scanner;
public class UserInputExample { public static void main(String[] args) { // Create a Scanner object to read input from the console Scanner scanner = new Scanner(System.in); // Prompt the user to enter their name System.out.print(“Enter your name: “); // Read the user’s input as a String String userName = scanner.nextLine(); // Prompt the user to enter their age System.out.print(“Enter your age: “); // Read the user’s input as an integer int userAge = scanner.nextInt(); // Display the user’s input System.out.println(“Hello, ” + userName + “! You are ” + userAge + ” years old.”); // Close the Scanner to prevent resource leaks scanner.close(); } } |
The above code uses the scanner class to take inputs from the user. Declare a scanner object, scn to store the input given by users. You can use different inbuilt user functions to take input based on different data types.
How to Take Input From users in Java: Inbuilt Functions in Scanner Class
Let us now check some of the inbuilt user functions in Java that accept different data types as input.
How to take input from user in Java: Inbuilt functions in Scanner Class | |
Method | Description |
int nextInt() | It is used to scan the next token of the input as an integer. |
float nextFloat() | It is used to scan the next token of the input as a float. |
double nextDouble() | It is used to scan the next token of the input as a double. |
byte nextByte() | It is used to scan the next token of the input as a byte. |
String nextLine() | Advances this scanner past the current line. |
boolean nextBoolean() | It is used to scan the next token of the input into a boolean value. |
long nextLong() | It is used to scan the next token of the input as a long. |
short nextShort() | It is used to scan the next token of the input as a Short. |
BigInteger nextBigInteger() | It is used to scan the next token of the input as a BigInteger. |
BigDecimal nextBigDecimal() | It is used to scan the next token of the input as a BigDecimal. |
How to take Input from user in Java: using Buffered Class
First, import the buggered reader class and input stream reader on your console. Now, you can easily take input from users using the BufferedReader class. Let us understand it using a code example given in the table below.
How to get input from user in Java: using Scanner class |
import java.io.BufferedReader;
import java.io.IOException; import java.io.InputStreamReader; public class UserInputExample { public static void main(String[] args) { // Create a BufferedReader object to read input from the user BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { // Prompt the user for input System.out.print(“Enter something: “); // Read the user input String userInput = reader.readLine(); // Display the user input System.out.println(“You entered: ” + userInput); } catch (IOException e) { e.printStackTrace(); } finally { try { // Close the BufferedReader in the finally block to avoid resource leaks if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } |
Using the buffered reader object class you can easily create a buffer object to read user input. Here, we need to use try and exception to raise exception error in case of IO exception.
The readerLine() method is used to read a line from the input text given by the user. Make sure to close the BufferedReader in the finally block to ensure the release of system resources.
Read More: What Is the Purpose of AJAX in JavaScript
How to take Input from user in Java: Inbuilt Functions in BufferReader Class
Check some major inbuilt functions used in the BufferReader class to take input from the users.
How to take input from user: Inbuilt functions in BufferReader Class | |
Method | Description |
int read() | It is used for reading a single character. |
int read(char[] cbuf, int off, int len) | It is used for reading characters into a portion of an array. |
boolean markSupported() | It tests the input stream support for the mark and reset method. |
String readLine() | It is used for reading a line of text. |
boolean ready() | It tests whether the input stream is ready to be read. |
long skip(long n) | It is used for skipping the characters. |
void reset() | It repositions the stream at a position where the mark method was last called on this input stream. |
void mark(int readAheadLimit) | It is used for marking the present position in a stream. |
void close() | It closes the input stream and releases any system resources associated with it. |
Difference between Scanner Class and BufferReader Class
Let us analyse both methods for taking user input to decide which one is more effective based on our use.
Difference between Scanner Class and BufferReader Class | |
Scanner Class | BufferReader Class |
Scanner is not is synchronous in nature and should be used only in a single-threaded case. | BufferReader is synchronous in nature. In a multithreading environment, BufferReader should be used. |
It can be imported using java.util packages. | It can be imported using java.io packages. |
The scanner has a small buffer of 1 KB char buffer. | BufferReader has a large buffer of 8 KB bytes as compared to Scanner. |
The scanner is a bit slower as it needs to parse data as well. | BufferReader is faster than Scanner, as it only reads a character stream. |
Scanner has methods like nextInt(), nextShort(), etc. | BufferReader has methods like parseInt(), parseShort(), etc. |
The scanner has the method nextLine() to read a line. | BufferReader has the method readLine() to read a line. |
For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group
How to take Input from User in Java FAQs
How to take input from users in Java?
You can easily take input in Java using the Scanner and BufferedReader Class.
Which class, Scanner or BufferReader, is better to take input in Java?
Scanner is useful in taking different data type inputs directly using nextInt(), nextDouble(), and other inbuilt classes. However, BufferReader provides an efficient way of reading character-based input lines.