Java User Input Scanner | String | Integer and Examples

How the calculator is working? Means how you can enter the numeric value for calculation and get the arithmetic solutions? It is possible because the application can read the input from the user. If you are beginners then sometimes you write a program about “Java User Input“, eg add the 2 numbers. We will see the example of adding and how Java User Input takes String and Integer from the system console.

Java User Input Scanner, String, Integer

Ways To Read Java Input

There are many ways to do it, some of are:-

  • Scanner Class in Java
  • Using Java Bufferedreader Class
  • Console Class in Java

Let’s start looking different Java User Input example

You will see all 4 methods to do read user input from the console with simples examples and basic details, one by one.

1. Scanner Class in Java

Java user input scanner class use to reading the input from the console. This is the most famous and favorite technique to take user input in java. For use scanner class, you have to import java.util package.

See below the example of Java user input string.

Output: A code structure and its output GIF.

Java User Input Scanner String
2. Using Java Bufferedreader Class

BufferedReader class  introduced in JDK1.0.

Output: Screenshot

Get user input using Java Bufferedreader Class
3. Console Class in Java

The Console class was introduced in Java 1.6. The methods like readLine() and readPassword() are provide by Console class.

Output: show error, because system.console() method required a console.

Console class in java error

Questions

Here is mostly common question asked in interviewer.

Q1. How to take input from a user in java using a scanner?

OR

How to pass input in java?

Answer: It’s easy just create Scanner object, create String variable and use nextLine() methods to read user input form console.

Q2. How to take input from a user in java without using a scanner class?

OR

How to take input from a user in java using BufferedReader?

Answer: If you don’t want to use Scanner class then you can use a BufferedReader to take input from a user. See the below code.

Q3. How to take integer input from a user in java?

Answer: In Scanner object using method nextInt() Reads an int value from the user. Let’s see the adding of 2 number example.

Output: Enter first number
7
Enter second number
8
Addition of number is: 15

Do comment if any doubt, suggestion or example.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java User Input Scanner Example Programs is in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.