DEV Community

Adrian Vrabie
Adrian Vrabie

Posted on

Hello World Driven Development: Reading in Java using System.in and adding two numbers!

Hello World Driven Development in Java.

All tutorials in Java start with System.out.println("Hello World!");.
The next obvious step is this problem: "Read two numbers from the keyboard and print their sum". Sounds trivial, doesn't it?

Have you wondered why all the tutorials are missing this part where you input something in Java from the Keyboard? Hint: "It's not that straightforward!"

Even in languages like C, only having #include <stdio.h> you can do scanf("%d",&x).
Try it in JAVA!

Of course there is the Scanner class.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

But Scanner class is not "batteries included" (ei java.lang which as you know is automatically included). You need to know it's part of the java.util package. And this Scanner class is a beast on its own: take a look at the imports it has within it: "java.io.; java.math.; java.nio.; java.nio.channels.;java.nio.charset.;java.nio.file.Path;java.nio.file.Files; java.util.regex.;" just to name a few!
And I don't know about you, but I don't like when "I need to know and use additional stuff" for such trivial problems.

So can you read in Java using less libraries? Yes, "java.io"
But it's kinda ugly:
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
Kinda funny, If you want to add 2 numbers from keyboard, you need to know about the "decorator pattern". :) Mind you, InputStreamReader reads characters. So you need something like: int x = Integer.parseInt(reader.readLine());.

OK, How about using System.in directly?
Q: Is it "batteries included"? A: yes!
And There is such thing as System.in.read()

Q: Is it easy to use? A: It Depends!
First of all, .in is another object: InputStream, part of java.io and is a "has a" of the System calss. And that InputStream is abstract! So who implements it? According to the docs: "Typically this stream corresponds to keyboard input or another input source specified by the host environment or user."
Secondly: System.in.read() reads only one byte and returns an int.
It's actually worse! The signature is:

public abstract int read() but it returns from -1 to 255! Internationalization made easy? Forget about it!
But read() is overridden by:
public abstract int read() throws IOException;
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) throws IOException
so you can write something more decent like:

byte[] input = new byte[30];
int read = System.in.read(input);
for (int i = 0; i < input.length; i++) {
if (input[i] == 10) break; // 10 is for Enter
System.out.print((char) input[i]);
}

So congratulations! Now you can type "hello world" and get it back on the "console"! You still can't add 2 numbers in Java though, you senior java developer!

Top comments (0)