Urgent.News

What's breaking now, across thousands of outlets.

Tech

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.

Read the original at dev.to →

More in Tech

3 Identity Checks When Staging DNS Records Reach the Wrong Production Zone

TL;DR: Treat a DNS change as a typed publication with three identities: environment, customer, and zone. Resolve all three from the request, compare them with independently loaded expectations, and…

  • Verify environment, customer, and zone identities separately
  • Halt write operation if identities do not align
  • Focus on zone reference, not just record value validity

Why I Created Xeno.JS: Architectural Rigor and Zero Infrastructure Constraints

Introduction How many times have you eagerly started a new TypeScript project, picked the trendy HTTP framework of the month, only to find yourself six months later with a chaotic monolith—hopelessly…

  • Xeno.JS merges .NET/C# architectural patterns with JavaScript's lightweight nature.
  • Implements strict separation of domain logic and infrastructure boundaries.
  • Runtime-agnostic, compatible with various environments without heavy Node.js reliance.

An $11,400 AWS bill, and CloudWatch Logs was $2,100 of it

I got access to the account on a Tuesday morning The founder had sent over credentials the night before with a message that said roughly: I think we're overpaying but I don't know where Total monthly…

  • $11,400 monthly AWS bill deemed excessive for 800 active users
  • $2,100 of the bill attributed to CloudWatch Logs with 43 unretained log groups
  • Debug logging disabled, $900 saved by deleting unused log groups

¿Puede una IA descifrar tu cifrado? La amenaza real es otra

La frase "hackeo con IA" se ha vuelto un titular que vende miedo, y al venderlo mezcla tres amenazas que son completamente distintas .

  • AI can't break well-designed encryption math
  • AI accelerates implementation bugs, social engineering, brute force
  • Real threat is quantum computing, not AI

More from Saturday 3 October →