#83 User Input using BufferedReader and Scanner in Java

Telusko
18 Jan 202311:48

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

00:00

📝 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.

05:01

🔍 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.

10:03

🔄 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

System.out.println is a method in Java used for printing output to the console. It is part of the PrintStream class and is accessed through the 'out' object, which is a static variable inside the System class. This method is fundamental to Java programming as it allows developers to display information in the console, and it is used in the script to demonstrate the concept of printing to the console.

💡Input

Input in the context of the video refers to the process of receiving data from the user. The script discusses how to take user input in Java, which is a crucial aspect of creating interactive applications. The video explains that while 'System.out.println' is used for output, 'System.in' is used for input, but it requires handling ASCII values and exceptions.

💡PrintStream

PrintStream is a class in Java that provides methods for printing objects to a text-output stream. The 'out' object, which is used to print to the console, is an instance of PrintStream. The video emphasizes that understanding the class from which 'println' is inherited is important for Java developers.

💡ASCII Value

ASCII Value refers to the numerical representation of a character according to the ASCII (American Standard Code for Information Interchange) standard. In the script, it is mentioned that when using 'System.in.read', the method returns the ASCII value of the character entered by the user, not the character itself, which is an important distinction when handling user input.

💡IOException

IOException is an exception that can be thrown in Java when an input or output operation fails. The video script explains that using 'System.in.read' can throw an IOException, which is a checked exception that must be handled by the developer, either through a try-catch block or by declaring the method to throw the exception.

💡BufferedReader

BufferedReader is a class in Java used for reading text from an input stream, such as the console or a file. The video script describes how to use BufferedReader to take user input in a more advanced way than 'System.in.read', by creating a buffered input stream that can handle larger inputs and is part of the java.io package.

💡InputStreamReader

InputStreamReader is a class in Java that provides a bridge between byte streams and character streams. In the context of the video, it is used in conjunction with BufferedReader to read input from the console. The script explains that an InputStreamReader object is needed to convert the input stream from 'System.in' into a format that BufferedReader can process.

💡Integer.parseInt

Integer.parseInt is a static method in Java that converts a string containing the representation of an integer into an actual integer value. The video script mentions using this method to convert the string returned by BufferedReader's 'readLine' method into an integer, which is necessary for numerical operations.

💡Scanner

Scanner is a class in Java introduced in version 1.5 that simplifies the process of reading input from various sources, including the console, files, and networks. The video script highlights Scanner as a more modern and convenient alternative to BufferedReader for taking user input, with methods like 'nextInt' that automatically convert input to integers.

💡Resource Management

Resource Management in the context of the video refers to the handling and closing of resources such as file streams or network connections. The script emphasizes the importance of closing resources like BufferedReader using the 'close' method to prevent resource leaks and ensure that resources are available for other processes.

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

play00:00

now it's a good time to talk about how

play00:02

to take input from the user I know you

play00:04

have been waiting for this one a long

play00:05

time because we have talked about

play00:07

different concepts and maybe you had

play00:10

this question in your mind okay

play00:11

everything looks good we talked about

play00:13

objects classes inheritance polymorphism

play00:15

but how do I take the input from the

play00:17

user because in between as well I've

play00:19

mentioned that what if this value comes

play00:20

from the user and the same point you

play00:22

might be thinking how Okay so let's try

play00:25

to answer that in this video so

play00:27

basically if you want to print something

play00:29

on the console so this is a console

play00:30

right on the right hand side whatever

play00:31

you have here it's a console and if you

play00:34

want to print something on the console

play00:36

what you do is you say

play00:38

system.out.print Ln right now you have

play00:40

to understand this first see print Ln is

play00:43

a method now if I ask you just to think

play00:45

about it print Ln method belongs to

play00:47

which class or it's a method of which

play00:49

class now this is the interview question

play00:51

a lot of people say that it is a class

play00:54

it's it's a method of system class but

play00:56

that's not the case see if I press my

play00:59

control button on when windows and

play01:01

command on Mac and if I click on this if

play01:03

I hover on this print Ln if I click on

play01:06

it you can see it gives you its

play01:07

definition it says print Ln and print Ln

play01:11

method belongs to print Stream So

play01:14

plainstream is a class and plain Talent

play01:16

is a method of print stream okay that

play01:19

means if you want to call Print Ln you

play01:21

first have to create object of a print

play01:23

stream but okay don't worry you don't

play01:25

have to create the object the beauty is

play01:27

the object is actually already created

play01:30

can you see that it we already have a

play01:32

out object and that's why we are using

play01:33

this object from a long time so out is

play01:36

the object of print stream but this

play01:39

object is created as a static variable

play01:42

inside the system class okay it's it's

play01:45

inside system class now since it is

play01:48

static so we can use out with the help

play01:49

of system dot out and once you have the

play01:52

access to the out object you can call

play01:53

println and that's what we have here

play01:56

system.out.println so if I want to print

play01:57

something if I want to print let's say

play01:59

hello of course I can do that and I can

play02:01

just compile this code and run it

play02:03

perfectly works

play02:05

now let's say I want to take the entry

play02:07

from the user I have to say hey enter a

play02:10

number now in this case when a user

play02:12

enters the number how will I accept it

play02:14

that that's tricky right so what do you

play02:17

think what could be a solution here what

play02:19

is the method we have to use now by any

play02:20

chance if you're coming from CC plus

play02:22

plus we use C out C in in C plus plus we

play02:26

use printf scanf in C right and it's

play02:29

straightforward right there are

play02:30

straightforward methods but in terms of

play02:32

java when you say system.out.printl and

play02:35

it prints right it is out and that's why

play02:36

it says out it is outputting so to input

play02:39

there should be in right let's see do we

play02:42

have in so if I go to system and if I

play02:45

scroll down to out yes there is out here

play02:48

and need to find in this is also in if

play02:51

you can see in is a static method and

play02:54

this object in is of type input stream

play02:57

oh we do have it okay so if I go back

play03:01

here and if I try to use system dot in

play03:05

dot oh there should be a method right

play03:07

because to print we have a print method

play03:09

for the input there should be read oh

play03:12

there is read okay great it works you

play03:14

can see we have a read method and read

play03:15

method returns a int value right it

play03:19

returns aint value that's great the only

play03:20

thing is it might throw an exception and

play03:23

if you can see which exception is IO

play03:24

exception and we know what is IO

play03:25

exception now so you have a choice you

play03:28

can handle the exception and this is

play03:30

checked exception which means you have

play03:31

to handle it it's your job to handle it

play03:33

compiler will force you to do that

play03:36

so you can either use try catch here or

play03:38

you can be evil and you can say throws

play03:41

exceptions not a good idea but it works

play03:44

for this code since we are learning so

play03:45

we can do that but when you are making

play03:47

an application don't do that try to use

play03:49

try catch here okay so system.in.read

play03:52

will give you the integer value that's

play03:53

great what I will do is I will just put

play03:56

that in a variable called num because it

play03:58

returns a value right read will give you

play04:00

the value so you have to put that in a

play04:02

variable and once you have the variable

play04:04

you can perform any operation if you

play04:06

want or you can print it that's your

play04:08

choice let's go back here and compile no

play04:12

problem

play04:13

if you try to read oh it says entire

play04:16

number I'm excited let's enter 5 and

play04:18

enter oh we got five but we also got

play04:22

three now that's weird I don't want

play04:25

three there okay let's try another

play04:27

number let's see with three oh we got

play04:29

fifty one what is happening here the

play04:31

thing is this system dot in dot read

play04:33

actually gives you the ASCII value for

play04:36

the number you enter example let's say

play04:38

if I run this code once again and if I

play04:40

enter capital A it prints 65. so every

play04:43

character on your keyboard has a ASCII

play04:45

value the same way for a Capital Area 65

play04:47

for small age is 97 I guess for 0 which

play04:52

is 48 example if I enter the value of 0

play04:55

it is 48 for Value 1 it is 49 so this

play04:59

goes on right so basically it is not

play05:01

giving you the exact value it is giving

play05:03

you the asciate representation of that

play05:04

value

play05:05

okay that is tricky actually so what one

play05:08

solution you have is what if you

play05:09

subtract the number by 48 or maybe it's

play05:13

not not 48 your subtract the number by

play05:15

48 not by 48 minus num it is none minus

play05:18

48 and now if you try to earn this call

play05:21

you have to first compile this code

play05:22

compile and run let's enter number five

play05:25

oh it works now can you see that because

play05:26

now we don't want to ASCII value we want

play05:28

whatever ask about you are getting by

play05:30

subtracting it right so if I enter six

play05:32

okay if I enter 6 it works okay now it

play05:38

works so we were able to manage it right

play05:39

this is not an ideal way of taking the

play05:41

input but that's what Java provides you

play05:43

Java says we will give you this method

play05:45

read which will give you ASCII value

play05:46

what if you want to get a bigger number

play05:48

what if you want to get example if I

play05:50

give a bigger number here let's say 55

play05:53

you can see it only gives you 5 because

play05:55

it reads only one character at a time oh

play05:58

that means if you want to read multiple

play06:00

characters we have to use a loop but

play06:02

let's not do that let's not take

play06:04

headache off by ourselves so Java says

play06:06

don't worry I will give you a

play06:09

specialized class to work with this so

play06:11

instead of using system.in dot read we

play06:14

have a special option which is there's a

play06:16

concept called buffered reader now

play06:18

buffer reader is basically a class which

play06:21

works with IO okay and it belongs to a

play06:24

package java.io so if you want to use

play06:25

buffer data you need to import this

play06:27

package so IO exception buffer data

play06:30

board belongs to IO package now whatever

play06:32

class we have used to allow most of them

play06:34

belong to java.lang which is Auto Import

play06:36

but if you want to use any class which

play06:39

is not there you have to explicitly

play06:41

mention the package name okay so let's

play06:42

create object or buffer data so we'll

play06:44

say buffer data BF is equal to new

play06:46

buffered reader

play06:48

okay but what next

play06:51

the thing is if you want to read we have

play06:53

to actually pass the in object can you

play06:55

see that if I go to Constructor buffer

play06:57

leader buffer data Constructor says okay

play07:00

I will work but first you have to pass

play07:02

an object of a reader okay now which

play07:04

date is talking about so basically there

play07:07

is one more class which you have to work

play07:08

with I know this code will be a bit

play07:10

lengthy because that's how Java is

play07:12

implemented it but let's use it in fact

play07:14

there is a better way as well which

play07:15

we'll see in the next topic so we have

play07:17

to pass the input stream reader so we

play07:20

have to get object of input stream

play07:22

reader let's say in in this case and I

play07:24

will say new input stream reader okay

play07:28

and whatever object you are creating

play07:29

here just pass it here your job is done

play07:32

but there's a problem you can see it

play07:34

input stream reader also needs an object

play07:36

of input stream okay in this case what

play07:38

you can do is it needs object of input

play07:40

stream right and if you remember when we

play07:42

talked about in object it is input

play07:45

stream object so what you can do here is

play07:47

you can pass system dot in I know it is

play07:51

bit complex and that's why in later

play07:53

version of java they have introduced

play07:55

better solution but I just want to show

play07:56

you this option as well which was there

play07:59

and people were using it for a long time

play08:00

okay so you have to say input stream

play08:03

reader in and then we have to get the

play08:05

object of input stream reader then you

play08:07

can create object of buffer data by

play08:08

passing the object of input stream now

play08:10

once you have it you can create a num

play08:13

variable and you can use buffered reader

play08:15

to read a line so you can see we have a

play08:18

read line the only thing is read line

play08:21

will give you the string okay we don't

play08:25

want string we want integer so to do

play08:28

that we have to use a special class

play08:29

called integer dot pass int which we

play08:32

have seen already and integer.pass int

play08:35

not in okay so whatever string you're

play08:37

getting basically you will get a number

play08:39

in the string format you just have to

play08:40

convert that into integer and now if I

play08:43

try to print number it should work

play08:45

otherwise we have wasted so much of time

play08:48

compile and run let's enter 55 it works

play08:52

doesn't matter how big your number is it

play08:54

will accept it you can say we got the

play08:55

number so basically this is how you take

play08:58

the input from the user there's another

play09:00

way which I will show you in some time

play09:01

but the important thing is whenever you

play09:03

use buffer leader it is trying to access

play09:05

input stream reader and the beauty is

play09:07

buffer data can take the input from

play09:09

anywhere not just from system keyboard

play09:12

it can also take input from the file

play09:13

from the network and you can mention

play09:15

wherever you want to take the input from

play09:17

you can mention it here you can mention

play09:19

the file you can mention all those other

play09:20

stuff now the thing is buffer reader

play09:22

whenever you're using it it's actually a

play09:24

resource now why it's a resource is

play09:26

because let's say when you are trying to

play09:27

read from a file of course file is a

play09:29

resource right and when you open the

play09:30

file it is your responsibility to close

play09:33

it when you open the network it is your

play09:35

responsibility to close it when you open

play09:36

the database connection it is your

play09:38

responsibility to close it how will you

play09:40

close it so once your job is done at the

play09:42

end you can just come back here and say

play09:44

BF Dot close consider we have a closed

play09:46

method so it is all always a good idea

play09:49

to close the resources again it's not

play09:52

compulsory it will not give you error

play09:54

but a good practice is close the

play09:56

resources okay otherwise you are making

play09:58

resources you are licking the file you

play10:00

are leaking data you are keeping the

play10:02

resource busy and the thing is if you

play10:04

are using a resource no one else can use

play10:06

it okay so don't do that don't be a evil

play10:08

person here so you close the resource

play10:10

okay so this is how you take the input

play10:12

and I know you are waiting for the

play10:13

better way of doing this let me show you

play10:16

a simple way so instead of using buffer

play10:18

data we can use one more technique here

play10:19

which is a scanner now scanner was

play10:22

introduced later in Java so if you can

play10:24

see if I go to scanner class scanner

play10:26

class was introduced in 1.5 so people

play10:29

before 1.5 were using buffer editor I

play10:31

know bad days but yeah we got scanner

play10:33

here we can create object of scanner

play10:35

let's say SC we can use any object name

play10:37

doesn't matter and we can say scanner

play10:39

now scanner takes the system dot in

play10:43

that's constant because we have to

play10:44

mention from where we are getting the

play10:46

input are you getting the input from the

play10:48

Soul are you getting the input from the

play10:49

file you have to mention that here and

play10:51

once you get this scanner object the

play10:53

beauty is in scanner you can say SC Dot

play10:56

and there are so many methods you can

play10:58

see that we got next line which will

play10:59

give you string you can say next int oh

play11:02

that means it automatically gives you

play11:03

integer value you can also say next

play11:05

chart uh it will it has so many methods

play11:08

but we are going to use next int not

play11:11

next line because if we use next line we

play11:13

have to pass that into integer so let's

play11:15

use next tint which will not create a

play11:17

lot of headache for us and run enter a

play11:20

number 567 and we got it so I know

play11:24

scanner looks much better than buffer

play11:25

leader but yeah it was introduced later

play11:27

so people before that were using buffer

play11:29

data so we have seen it in fact in the

play11:31

next video we'll try to understand more

play11:33

about how do you close the sources okay

play11:36

and that's why we are teaching this

play11:37

concept now because now we know what is

play11:39

IO exception and all those stuff so yeah

play11:41

you have two choice of taking the input

play11:43

from the user you can use buffer Twitter

play11:45

or you can use a scanner class

Rate This

5.0 / 5 (0 votes)

الوسوم ذات الصلة
Java InputConsole IOBufferedReaderScanner ClassUser InteractionASCII ValuesInput MethodsProgramming TutorialIO ExceptionResource ManagementJava 1.5
هل تحتاج إلى تلخيص باللغة الإنجليزية؟