How to Take Input from User in Java
I know why you are here. To learn about Scanner Class Java and how to take input from user in Java. I promise you shall get exactly what you are here for. Thy will be done!
In the previous chapter, we had learned all about how to add two numbers that were already there with you. What if the user wishes to choose his own pair of numbers? How do we input our own choice?
That’s exactly what we are going to see hereby.
How to Take Input from User in Java
In order to learn how to take input from user in Java we need to first understand how many ways are out there to do so. Then we are going to learn about their individual syntaxes and then finally move on to examples.
There are four different ways to take input from user in Java. And yes they are all tucked under their very own classes. These are namely:
- Scanner Class
- BufferedReader and InputStreamReader Class
- DataInputStream Class
- Console Class
We are going to look at each one of them one at a time. So put your seat belts on. This is going to be one bumpy ride.
Scanner Class
There is a class called Scanner in Java that can be used to take inputs from the user. There are some predefined methods in this class that take the input depending upon data types.
The most commonly used methods from Scanner Class are these two blokes:
- String next()
- int nextInt()
While the first one can only grab one series of string till a ‘space’ is encountered, we often use its better alternative “String nextLine()” to capture one whole line irrespective of spaces. As you might have guessed already the return type here is String.
We are going to take a look at how things work by implementing the String next() method first and see if we can display whatever input we give in the console.
When working with Scanner classes, we need to create an instance of the Scanner class first. The same holds true for all the other methods of deriving inputs.
The syntax that we need to follow hereby is:
Scanner scan = new Scanner(System.in)
The only absurd and unusual thing for you in the above syntax should be System.in. The rest of things, I am guessing, you already know about since we have been working on it for a while. If you still don’t know what they are, you can go back and check what’s what in the chapter about classes and objects.
System.in is nothing but an Inputstream that has been programmed to take inputs from the keyboard via a console program. You don’t have to worry about how, because Java has been hard coded to work like that. You will learn more about Inputstreams in the later part of this chapter, so chill!
Steps to Use Scanner Class
First let’s go through the steps on how to take input from user in Java. We will see how to obtain a string output first:
Hope you have Eclipse open, and you are past the creation of a project, a package and a class with a public static void main() method waiting for your inputs.
Step 1: Type “import java.util.Scanner;” write underneath your package. We need to specify this since Java wouldn’t understand where to look for the Scanner class. That’s the first step to do.
Step 2: Time to declare the Scanner class with the creation of an object. I am going to name my object “scan” for ease of remembrance. Declare it with the syntax we had learnt above.
Step 3: Let’s use one method of Scanner class called String next() so as to see if we could expect keyboard inputs in a variable of our choice.
Step 4: Time to display whatever input we had roped in, in our variable ‘s’. Use the infamous System.out to display the variable.
Step 5: Now your eclipse might be throwing a warning of closing the Scanner class. It’s a good habit to close our objects once our job is done. It helps in efficiency as well as uses only a required memory space.
So I am going to go ahead and add scan.close() in the end. Just so we follow rules and stay safe on all accounts. So the final look that your Eclipse must be giving you might appear something like this:
Run the Program
Step 6: Time to run it now. Go ahead and run the program by clicking on that Green Run Button.
Now it might appear weird because it looks like nothing happened, but trust me it did. In the console down below, it’s been prompting you to enter something.
I am gonna go ahead and write, “Justin Bieber is a little girl.”
Let’s see what happens.
Hey! That’s not fair!
When I pressed Enter it just wrote “Justin” back, as if the computer doesn’t know anything about him being a lil girl.
Remember how I talked about the usage of nextLine() earlier, when you wish to grab all the spaces too. Well we are going to make that simple change here, and how see things fair then.
Step 7: Change next() to nextLine()
There! Eclipse approves!
Now I can die in peace.
BufferedReader and InputStreamReader Class
Even though Scanner class is one of the easiest ways to work around with, people have often complained about synchronization issues. That’s why the multitude prefers BufferedReader and InputStreamReader class method to take inputs in Java.
There are two types of classes in Input and Output in Java. They are:
- Streams
- Readers/Writers
Streams are for reading and writing binary data whereas Readers/Writers are for reading and writing characters. They are a layer above the streams that convert binary to characters and then back. Reading byte by byte data from the disk is not the right way and it takes away a lot of memory too, and hence the concept of buffer came into existence.
Buffer is a place where all of your data is put in at one time. Looking through it saves you time. It saves you memory. Also, it is more efficient.
The syntax to remember here is:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
InputStreamReader is a Class in Java that reads bytes and decodes them into characters. So here it will take input from System.in (the inputstream here the keyboard) and convert it into characters, then will wrap it into the class called BufferedReader.
BufferedReader is a class that simply puts things in a buffer so as to save memory, and making it easier to read them therefrom.
That being said even if we would have gone with:
InputStreamReader is = new InputStreamReader(System.in);
Java would have still been successful in retrieving information. However, it would have failed to convert it into string since there are no such methods defined under the inputstream.
So sticking to the original we will start with the generation of steps on how to take input from user in Java using BufferedReader and InputStreamReader Class.
Steps to use BufferedReader and InputStreamReader in Java
Step 1: The first step is to import java.io.*. You could alternatively import individual classes from java.io. too but if you use the asterisk sign, it will automatically import both the classes, saving you from any issues.
Go ahead and write import.java.io.*; right underneath the package.
Step 2: Now it is time to use the aforesaid syntax in the main method. Go ahead and paste it there:
Step 3: There is this String method readLine() of BufferedReader class that reads your stuff and returns it in String format. Our next step is to call that method and assign it to a string.
Exception
Notice how there is an error underline underneath our method. Eclipse is smart enough to tell us what’s going to be the issue if we try to call this method. It might give us nothing too. If that’s the case then we need to be prepared for that.
That’s where Exceptions come into play.
Exceptions are nothing but impending issues in our code. If we don’t foresee and address it beforehand then it might cause our code to terminate abruptly. Foreseeing it and addressing it beforehand is called Exception Handling. We will learn more about how to handle exceptions in the upcoming chapters.
Step 4: For now just know that if you click on the yellow bulb button to abate your error, it will suggest two ways to handle it. Click on the first “Add throws declaration”. It will automatically add the clause “throws IOException” against your main method. Your code might look like this now:
Step 5: Time to display the code. Write System.out.println(s); to print whatever ‘s’ might capture. When you are done adding this line go ahead and run the code.
Type in anything you want in the console and press Enter. See if it is being displayed or not.
Pretty cool, huh?
DataInputStream Class
Yet another method to read input, however, DataInputStream class is only concerned with primitives. But to learn how to take input from user in Java you must walk on this path too.
You could read String too with it using readLine() but unfortunately readLine() method has been deprecated. Hence people often make use of BufferedReader to read String inputs.
But if you try to run the program using readLine() it still works nevertheless despite the deprecation warning:
It did work!
Console Class
This takes us to the final method of how to take input from user in Java. Console as you might have already guessed is the one where we have been typing our data so far. Console Class is widely used owing to its feature of not echoing the data when reading inputs, and hence it’s great for administering security.
The syntax here to use the Console class is:
Console console = System.console();
Oh before we forget this doesn’t work in an IDE. So I am going to run it in an actual console – “cmd”.
Step 1: Write the above code in a text document file. Yes like we used to. It must look something like this after you have appended a class and main method.
Step 2: Add readLine() method to read whatever will be typed in a variable ‘s’. Make it String.
Step 3: Display the String by using the System.out.println command.
Step 4: Save the file as “classname.java”. Open cmd. Navigate to your folder, and then compile using javac and then run the program.
So which one seems to be the one you have been looking for all your life? Which one seems the perfect answer for how to take input from user in Java? I think each one of them have their own set of benefits and you will realize that based on the project you are working on.
For now I am glad that we have learnt how to take input from user in Java, and I think that’s an achievement per se.
Alright, use that. I am gonna take a rest. I feel knackered after this unrelenting session.
2 Responses
[…] we not just learn how to take input from user in Java in the last chapter? It would be only befitting to learn how to read a text file in […]
[…] input using the Scanner class. If you have forgotten about how to take inputs you can refer my chapter about Scanner class […]