Reading Input in Java
System.in, BufferedReader, and Scanner Every Java beginner eventually asks the same question: "Okay, I can print output — how do I actually read something the user types?" Java gives you a few ways to do this, each with trade-offs. Let's go through them in the order most people discover them. A quick trivia detour: what is println , really? Before we get to input, a fun fact that doubles as a…
When embarking on the journey of reading user input in Java, a common conundrum confronts every beginner: how does one actually capture the characters a user types? Java provides several avenues to accomplish this, each with its own set of trade-offs. Let's embark on a journey through these methods, in the order they typically come across.
Before we delve into input, a fascinating tidbit awaits: ponder the class to which `println` belongs. The answer is `PrintStream`. When you invoke `System.out.println(...)`, you're actually calling the `println` method on `System.out`, an object inheriting from `PrintStream`. Interestingly, `System.out` commences its existence as a `null` object within the `System` class.
It only morphs into a functional entity due to native JVM code initializing it during program startup. This serves as a testament to the extensive setup that transpires before even the `main` method initiates execution.
The most rudimentary method to read input is `System.in.read()`. This reads a solitary byte and returns it as an integer. In a sample program, it's employed like so:
```java
System.out.println("Enter a Number: ");
int number = System.in.read();
System.out.println("You entered: " + (number - 48));
```
Here, the `- 48` operation might seem peculiar. This is because `read()` returns the ASCII value of the typed character, not the numeric value itself. In ASCII, the character '0' equates to 48, '1' to 49, and so forth. Thus, subtracting 48 translates the ASCII code back into the actual digit. However, this method's effectiveness is limited to single-digit inputs.
As soon as users input multi-digit numbers such as '42', the approach fails — it reads the '4' and ceases, oblivious to the trailing '2'. For handling inputs beyond single digits, a more robust solution is required.
A more pragmatic approach involves `BufferedReader`. Importing the necessary classes:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
```
We instantiate a `BufferedReader` using `InputStreamReader` wrapped around `System.in`. This allows `BufferedReader` to read entire lines of text at once, using the `readLine()` method. The line of text can subsequently be converted into the desired type, as demonstrated here:
```java
int num = Integer.parseInt(bfNumber.readLine());
```
While `BufferedReader` is versatile enough to read input from sources beyond the console — files, network connections, etc. — it's crucial to remember to close this resource once its purpose is fulfilled, to prevent potential leaks. This can be done through manual `close()` invocation, though this method poses risks of unreleased resources in case of exceptions occurring before the call.
The solution to this issue lies in the introduction of try-with-resources, which automates resource management, ensuring closure even in the face of exceptions.
Java 5 introduced the `Scanner` class, offering a more user-friendly alternative for reading console input:
```java
import java.util.Scanner;
```
Incorporating `Scanner` into our program simplifies the process:
```java
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
System.out.println("You entered: " + num);
reader.close();
```
Here, `nextInt()` performs both the reading and conversion to an integer in a single step, eliminating the need for manual parsing. `Scanner` extends this convenience to other data types, providing methods like `nextLine()`, `nextDouble()`, `nextBoolean()`, and more.
In conclusion, while `System.in.read()` serves as an educational tool to understand the fundamentals of input handling, it's largely impractical for real-world applications due to its limitations. Conversely, while `Scanner` simplifies input handling significantly, it's essential to recognize its potential for misuse, such as excessive memory consumption with large inputs. Nonetheless, for most straightforward input scenarios, `Scanner` presents an efficient and intuitive solution.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.