#83 User Input using BufferedReader and Scanner in Java
Summary
TLDRThis video script delves into Java's methods for taking user input, contrasting the traditional `System.in.read` method, which returns ASCII values, with the more modern and user-friendly `Scanner` class introduced in Java 1.5. It explains the complexities of handling `IOException` and the importance of closing resources like `BufferedReader` to prevent data leaks. The script provides a step-by-step guide on using both `BufferedReader` and `Scanner` for input, highlighting the simplicity and efficiency of the latter.
Takeaways
- π System.out.println is a method that belongs to the PrintStream class, which is used for outputting text to the console.
- π The System class contains a static PrintStream object named 'out', which is used to call the println method without creating an object.
- β To take input from the user in Java, one can use the System.in object, which is of type InputStream and has a 'read' method.
- π’ The read method returns an int value representing the ASCII value of the character entered by the user, not the actual number.
- π‘ To convert the ASCII value to an actual number, subtract 48 from the read value, e.g., 'int num = read - 48;'.
- π« The read method can only read one character at a time, which may not be suitable for larger numbers or strings.
- π Java provides the BufferedReader class for reading multiple characters at once, which can be used with an InputStreamReader.
- π BufferedReader requires the user to import the java.io package and pass an InputStreamReader object to its constructor.
- π When using BufferedReader, the readLine method returns a string, which can be converted to an integer using Integer.parseInt.
- π Scanner class, introduced in Java 1.5, simplifies input by providing methods like nextInt() that automatically parse the input into the desired data type.
- π Both BufferedReader and Scanner need to be closed after use to free up system resources, preventing resource leaks and allowing others to use the resources.
Q & A
What is the purpose of the 'println' method in Java?
-The 'println' method in Java is used to print text to the console. It is a method of the PrintStream class, accessed through the 'out' object which is a static variable inside the System class.
How does Java handle user input from the console?
-Java uses the 'in' object of the InputStream class to handle user input from the console. The 'read' method of the InputStream class returns an int value representing the ASCII value of the input character.
What is the issue with using 'System.in.read' for taking user input?
-The 'System.in.read' method returns the ASCII value of the input character, not the actual character or number. This can be problematic when trying to read numerical input directly.
How can you convert the ASCII value returned by 'System.in.read' to an actual number?
-To convert the ASCII value to an actual number, you can subtract 48 from the ASCII value. This works because the ASCII value for '0' is 48, and the values for other digits increase by 1 from there.
What is the BufferedReader class used for in Java?
-The BufferedReader class is used for reading text from an input stream, such as the console. It allows for reading lines of text and can handle larger inputs compared to 'System.in.read'.
Why do we need to import the java.io package to use BufferedReader?
-The java.io package contains the BufferedReader class, along with other I/O classes like IOException. Importing this package is necessary to use these classes in your Java program.
How does the BufferedReader work with the InputStreamReader?
-The BufferedReader is constructed with an InputStreamReader object, which in turn is constructed with an InputStream object, such as 'System.in'. This setup allows the BufferedReader to read from the console input stream.
What is the advantage of using BufferedReader over 'System.in.read'?
-BufferedReader allows for reading an entire line of text as a String, making it easier to handle multi-character inputs. It also provides methods to convert the String to other data types, like integers, without dealing with ASCII values.
What is the Scanner class in Java and how is it used for input?
-The Scanner class, introduced in Java 1.5, is a more modern way to handle user input. It can read different types of input directly, such as integers or strings, without the need for manual conversion from ASCII values.
Why is it important to close resources like BufferedReader or Scanner after use?
-Closing resources like BufferedReader or Scanner is important to free up system resources. It prevents resource leaks and ensures that the resources are available for other parts of the program or other programs to use.
Outlines
π Understanding User Input in Java
This paragraph discusses how to take user input in Java, a topic that has been anticipated by the audience. It explains the process of printing to the console using the `System.out.println` method, which is part of the `PrintStream` class. The speaker clarifies a common misconception that `println` is a method of the `System` class, instead revealing that it's actually from `PrintStream`. The `out` object, which is used to print to the console, is a static variable in the `System` class. The paragraph also introduces the concept of taking input from the user, which traditionally involves the `System.in.read` method, but notes that this method returns the ASCII value of the input character, not the actual number entered. The speaker suggests handling this by subtracting 48 from the ASCII value to get the correct integer input.
π Advanced User Input Techniques in Java
The second paragraph delves into more advanced methods for handling user input in Java. It introduces the `BufferedReader` class, which is part of the `java.io` package, as a way to read input from various sources, not just the keyboard. The speaker explains the process of creating a `BufferedReader` object and using it to read a line of input, which requires converting the resulting string to an integer using `Integer.parseInt`. The paragraph also touches on the importance of closing resources after use to prevent resource leaks. Towards the end, the speaker mentions an alternative, simpler method for taking user input that will be discussed in a future video, hinting at the introduction of the `Scanner` class in later versions of Java.
π Introducing Scanner for Simplified Input in Java
The final paragraph introduces the `Scanner` class, which was added to Java in version 1.5, as a more user-friendly way to handle input compared to `BufferedReader`. The speaker demonstrates how to create a `Scanner` object and use it to read different types of input, such as integers, directly without needing to convert from a string. The `Scanner` class automatically handles the conversion from the input string to the desired data type. The paragraph emphasizes the ease of use of `Scanner` and its ability to read from various input sources, including the console, files, and networks. It concludes by comparing the two methods of taking user input, `BufferedReader` and `Scanner`, and sets the stage for further exploration of resource management in subsequent videos.
Mindmap
Keywords
π‘System.out.println
π‘Input
π‘PrintStream
π‘ASCII Value
π‘IOException
π‘BufferedReader
π‘InputStreamReader
π‘Integer.parseInt
π‘Scanner
π‘Resource Management
Highlights
Introduction to taking user input in Java, a common question among learners.
Explanation of `System.out.println` as a method belonging to the `PrintStream` class.
Clarification that `System.out` is a static variable inside the `System` class, representing a `PrintStream` object.
Demonstration of printing to the console using `System.out.println`.
Introduction to taking input from the user with the `System.in.read` method.
The `System.in.read` method returns the ASCII value of the input character, not the character itself.
Solution to convert ASCII values to actual numbers by subtracting 48.
Limitation of `System.in.read` as it reads only one character at a time.
Introduction to the `BufferedReader` class for handling multiple character inputs.
Explanation of creating a `BufferedReader` object and its relationship with `InputStreamReader` and `System.in`.
Using `BufferedReader.readLine` to read a whole line of input and converting it to an integer.
The importance of closing resources like `BufferedReader` to prevent resource leakage.
Introduction to the `Scanner` class as a more modern and convenient way to take user input.
Demonstration of using `Scanner.nextInt` to directly read integer values from user input.
Comparison between `BufferedReader` and `Scanner`, highlighting the ease of use of `Scanner`.
Emphasis on the good practice of closing input streams and resources after use.
Announcement of a future topic on understanding IO exceptions and resource management.
Transcripts
now it's a good time to talk about how
to take input from the user I know you
have been waiting for this one a long
time because we have talked about
different concepts and maybe you had
this question in your mind okay
everything looks good we talked about
objects classes inheritance polymorphism
but how do I take the input from the
user because in between as well I've
mentioned that what if this value comes
from the user and the same point you
might be thinking how Okay so let's try
to answer that in this video so
basically if you want to print something
on the console so this is a console
right on the right hand side whatever
you have here it's a console and if you
want to print something on the console
what you do is you say
system.out.print Ln right now you have
to understand this first see print Ln is
a method now if I ask you just to think
about it print Ln method belongs to
which class or it's a method of which
class now this is the interview question
a lot of people say that it is a class
it's it's a method of system class but
that's not the case see if I press my
control button on when windows and
command on Mac and if I click on this if
I hover on this print Ln if I click on
it you can see it gives you its
definition it says print Ln and print Ln
method belongs to print Stream So
plainstream is a class and plain Talent
is a method of print stream okay that
means if you want to call Print Ln you
first have to create object of a print
stream but okay don't worry you don't
have to create the object the beauty is
the object is actually already created
can you see that it we already have a
out object and that's why we are using
this object from a long time so out is
the object of print stream but this
object is created as a static variable
inside the system class okay it's it's
inside system class now since it is
static so we can use out with the help
of system dot out and once you have the
access to the out object you can call
println and that's what we have here
system.out.println so if I want to print
something if I want to print let's say
hello of course I can do that and I can
just compile this code and run it
perfectly works
now let's say I want to take the entry
from the user I have to say hey enter a
number now in this case when a user
enters the number how will I accept it
that that's tricky right so what do you
think what could be a solution here what
is the method we have to use now by any
chance if you're coming from CC plus
plus we use C out C in in C plus plus we
use printf scanf in C right and it's
straightforward right there are
straightforward methods but in terms of
java when you say system.out.printl and
it prints right it is out and that's why
it says out it is outputting so to input
there should be in right let's see do we
have in so if I go to system and if I
scroll down to out yes there is out here
and need to find in this is also in if
you can see in is a static method and
this object in is of type input stream
oh we do have it okay so if I go back
here and if I try to use system dot in
dot oh there should be a method right
because to print we have a print method
for the input there should be read oh
there is read okay great it works you
can see we have a read method and read
method returns a int value right it
returns aint value that's great the only
thing is it might throw an exception and
if you can see which exception is IO
exception and we know what is IO
exception now so you have a choice you
can handle the exception and this is
checked exception which means you have
to handle it it's your job to handle it
compiler will force you to do that
so you can either use try catch here or
you can be evil and you can say throws
exceptions not a good idea but it works
for this code since we are learning so
we can do that but when you are making
an application don't do that try to use
try catch here okay so system.in.read
will give you the integer value that's
great what I will do is I will just put
that in a variable called num because it
returns a value right read will give you
the value so you have to put that in a
variable and once you have the variable
you can perform any operation if you
want or you can print it that's your
choice let's go back here and compile no
problem
if you try to read oh it says entire
number I'm excited let's enter 5 and
enter oh we got five but we also got
three now that's weird I don't want
three there okay let's try another
number let's see with three oh we got
fifty one what is happening here the
thing is this system dot in dot read
actually gives you the ASCII value for
the number you enter example let's say
if I run this code once again and if I
enter capital A it prints 65. so every
character on your keyboard has a ASCII
value the same way for a Capital Area 65
for small age is 97 I guess for 0 which
is 48 example if I enter the value of 0
it is 48 for Value 1 it is 49 so this
goes on right so basically it is not
giving you the exact value it is giving
you the asciate representation of that
value
okay that is tricky actually so what one
solution you have is what if you
subtract the number by 48 or maybe it's
not not 48 your subtract the number by
48 not by 48 minus num it is none minus
48 and now if you try to earn this call
you have to first compile this code
compile and run let's enter number five
oh it works now can you see that because
now we don't want to ASCII value we want
whatever ask about you are getting by
subtracting it right so if I enter six
okay if I enter 6 it works okay now it
works so we were able to manage it right
this is not an ideal way of taking the
input but that's what Java provides you
Java says we will give you this method
read which will give you ASCII value
what if you want to get a bigger number
what if you want to get example if I
give a bigger number here let's say 55
you can see it only gives you 5 because
it reads only one character at a time oh
that means if you want to read multiple
characters we have to use a loop but
let's not do that let's not take
headache off by ourselves so Java says
don't worry I will give you a
specialized class to work with this so
instead of using system.in dot read we
have a special option which is there's a
concept called buffered reader now
buffer reader is basically a class which
works with IO okay and it belongs to a
package java.io so if you want to use
buffer data you need to import this
package so IO exception buffer data
board belongs to IO package now whatever
class we have used to allow most of them
belong to java.lang which is Auto Import
but if you want to use any class which
is not there you have to explicitly
mention the package name okay so let's
create object or buffer data so we'll
say buffer data BF is equal to new
buffered reader
okay but what next
the thing is if you want to read we have
to actually pass the in object can you
see that if I go to Constructor buffer
leader buffer data Constructor says okay
I will work but first you have to pass
an object of a reader okay now which
date is talking about so basically there
is one more class which you have to work
with I know this code will be a bit
lengthy because that's how Java is
implemented it but let's use it in fact
there is a better way as well which
we'll see in the next topic so we have
to pass the input stream reader so we
have to get object of input stream
reader let's say in in this case and I
will say new input stream reader okay
and whatever object you are creating
here just pass it here your job is done
but there's a problem you can see it
input stream reader also needs an object
of input stream okay in this case what
you can do is it needs object of input
stream right and if you remember when we
talked about in object it is input
stream object so what you can do here is
you can pass system dot in I know it is
bit complex and that's why in later
version of java they have introduced
better solution but I just want to show
you this option as well which was there
and people were using it for a long time
okay so you have to say input stream
reader in and then we have to get the
object of input stream reader then you
can create object of buffer data by
passing the object of input stream now
once you have it you can create a num
variable and you can use buffered reader
to read a line so you can see we have a
read line the only thing is read line
will give you the string okay we don't
want string we want integer so to do
that we have to use a special class
called integer dot pass int which we
have seen already and integer.pass int
not in okay so whatever string you're
getting basically you will get a number
in the string format you just have to
convert that into integer and now if I
try to print number it should work
otherwise we have wasted so much of time
compile and run let's enter 55 it works
doesn't matter how big your number is it
will accept it you can say we got the
number so basically this is how you take
the input from the user there's another
way which I will show you in some time
but the important thing is whenever you
use buffer leader it is trying to access
input stream reader and the beauty is
buffer data can take the input from
anywhere not just from system keyboard
it can also take input from the file
from the network and you can mention
wherever you want to take the input from
you can mention it here you can mention
the file you can mention all those other
stuff now the thing is buffer reader
whenever you're using it it's actually a
resource now why it's a resource is
because let's say when you are trying to
read from a file of course file is a
resource right and when you open the
file it is your responsibility to close
it when you open the network it is your
responsibility to close it when you open
the database connection it is your
responsibility to close it how will you
close it so once your job is done at the
end you can just come back here and say
BF Dot close consider we have a closed
method so it is all always a good idea
to close the resources again it's not
compulsory it will not give you error
but a good practice is close the
resources okay otherwise you are making
resources you are licking the file you
are leaking data you are keeping the
resource busy and the thing is if you
are using a resource no one else can use
it okay so don't do that don't be a evil
person here so you close the resource
okay so this is how you take the input
and I know you are waiting for the
better way of doing this let me show you
a simple way so instead of using buffer
data we can use one more technique here
which is a scanner now scanner was
introduced later in Java so if you can
see if I go to scanner class scanner
class was introduced in 1.5 so people
before 1.5 were using buffer editor I
know bad days but yeah we got scanner
here we can create object of scanner
let's say SC we can use any object name
doesn't matter and we can say scanner
now scanner takes the system dot in
that's constant because we have to
mention from where we are getting the
input are you getting the input from the
Soul are you getting the input from the
file you have to mention that here and
once you get this scanner object the
beauty is in scanner you can say SC Dot
and there are so many methods you can
see that we got next line which will
give you string you can say next int oh
that means it automatically gives you
integer value you can also say next
chart uh it will it has so many methods
but we are going to use next int not
next line because if we use next line we
have to pass that into integer so let's
use next tint which will not create a
lot of headache for us and run enter a
number 567 and we got it so I know
scanner looks much better than buffer
leader but yeah it was introduced later
so people before that were using buffer
data so we have seen it in fact in the
next video we'll try to understand more
about how do you close the sources okay
and that's why we are teaching this
concept now because now we know what is
IO exception and all those stuff so yeah
you have two choice of taking the input
from the user you can use buffer Twitter
or you can use a scanner class
5.0 / 5 (0 votes)