In the Java program, there are 3 ways we can read input from the user in the command line environment to get user input, Java BufferedReader Class, Java Scanner Class, and Console class. Let us discuss the classes in detail. We use the Scanner class to obtain user input. This program asks the user to enter an integer, a string, and float, and it will be printed on display. The scanner class in java.util is present so that we can add this package to our software. First, we create a Scanner Class object and use the Scanner Class method.
3 Ways of Java User Input
There are three ways to read the User Input:
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
- Java BufferedReader Class
- Java Scanner Class
- Using console Class
These three class are mentioned below; let us discuss them in detail:
1. Java BufferedReader Class
It extends reader class. BufferedReader reads input from the character-input stream and buffers characters so as to provide an efficient reading of all the inputs. The default size is large for buffering. When the user makes any request to read, the corresponding request goes to the reader, and it makes a read request of the character or byte streams; thus, BufferedReader class is wrapped around another input streams such as FileReader or InputStreamReaders.
For example:
BufferedReader reader = new BufferedReader(new FileReader("foo.in"));
BufferedReader can read data line by line using the method readLine() method.
BufferedReader can make the performance of code faster.
Constructors
BufferedReader has two constructors as follows:
1. BufferedReader(Reader reader): Used to create a buffered input character stream that uses the default size of an input buffer.
2. BufferedReader(Reader reader, input size): Used to create a buffered input character stream that uses the size provided for an input buffer.
Functions
- int read: It is used for reading a single character.
- int read(char[] cbuffer, int offset, int length): It is used for reading characters in the specified part of an array.
- String readLine (): Used to reading input line by line.
- boolean ready(): Used to test whether the input buffer is ready to read.
- long skip: Used for skipping the characters.
- void close(): It closes the input stream buffer and system resources associated with the stream.
When the user enters the character from the keyboard, it gets read by the device buffer and then from System.in it passes on to the buffered reader or input stream reader and gets stored in the input buffer.
Code:
import java.util.*; import java.lang.*; import java.io.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /*package whatever //do not write package name here */ class BufferedReaderDemo { public static void main (String[] args) throws NumberFormatException, IOException { System.out.println("Enter your number"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); System.out.println("Number you entered is: " + t); System.out.println("Enter your string"); String s = br.readLine(); System.out.println("String you entered is: " + s); } }
Output:
Program with reading from InputStreamReader and BufferedReader:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferedReaderDemo { public static void main(String args[]) throws IOException{ InputStreamReader reader = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(reader); System.out.println("What is your name?"); String name=br.readLine(); System.out.println("Welcome "+name); } }
Output:
2. Java Scanner Class
java.util. scanner class is one of the classes used to read user input from the keyboard. It is available at the util package. Scanner classes break the user input using a delimiter that is mostly whitespaces by default. The scanner has many methods to read console input of many primitive types such as double, int, float, long, Boolean, short, byte, etc. It is the simplest way to get input in java. Scanner class implements Iterator and Closeable interfaces. The scanner provides nextInt() and many primitive type methods to read inputs of primitive types. The next() method is used for string inputs.
Constructors
- Scanner(File source): It constructs a scanner to read from a specified file.
- Scanner(File source, String charsetName): It constructs a scanner to read from a specified file.
- Scanner(InputStream source), Scanner(InputStream source, String charsetName): It constructs a scanner to read from a specified input stream.
- Scanner(0Readable source): It constructs a scanner to read from a specified readable source.
- Scanner(String source): It constructs a scanner to read from a specified string source.
- Scanner(ReadableByteChannel source): It constructs a scanner to read from a specified channel source.
- Scanner(ReadableByteChannel source, String charsetName): It constructs a scanner to read from a specified channel source.
Functions
Below are mentioned the method to scan the primitive types from console input through Scanner class.
- nextInt(),
- nextFloat(),
- nectDouble(),
- nextLong(),
- nextShort(),
- nextBoolean(),
- nextDouble(),
- nextByte(),
Program to read from Scanner Class:
Using scanner class. import java.util.Scanner; /*package whatever //do not write package name here */ class ScannerDemo { public static void main (String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your number"); int t = sc.nextInt(); System.out.println("Number you entered is: " + t); System.out.println("Enter your string"); String s = sc.next(); System.out.println("String you entered is: " + s); } }
Output:
3. Using console Class
Using the console class to read the input from the command-line interface. It does not work on IDE.
Code:
public class Main { public static void main(String[] args) { // Using Console to input data from user System.out.println("Enter your data"); String name = System.console().readLine(); System.out.println("You entered: "+name); } }
Output:
The above is the detailed content of Java User Input. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
