Instructor (Mehran Sahami): All right, welcome back to yet another fun-filled exciting day of cs106a. This is the pivot Ė this is the turning point of the quarter. This is like the pivot of the quarter. After today, itís all downhill, because weíve gone through just as many days as we have left. Fairly exciting. As a matter of fact, they actually have fewer days left, because we have like the last class is not happening and stuff.
But a few announcements before we delve into things today. The handouts from last time, if you didnít get the handouts from last time, namely, especially the practice midterm and solutions to the practice midterm as well as assignment No. 4, if you didnít get those, theyíre available in the back today. If you already got them, you donít need to pick up additional copies. Thereís no additional handouts for today, but there are just copies of the ones from last week.
So, again, with the practice midterm, I would very highly encourage you to take it and, if you want, also, for the full effect, actually time yourself doing it so you get some notion of whatís taking you longer or whatís taking less time. That will give you a diagnostic of the kind of things you need to brush up on, so Ė and itíll also give you a chance to see what weíre really kind of expecting for the midterm, and there was a bunch of stuff on there where it explains that the midterm is open book and open note, but closed computer, and all the guidelines for the midterm are all explained on the first page of that handout.
So the midterm is coming up. Itís next week, just a few days away. Tuesday, October 30th, 7:00 p.m. to 8:30 p.m. in Kresge Auditorium. If you donít know where Kresge Auditorium is, find out where Kresge Auditorium is. Itís your friend, itís big, itís bad, itís Kresge. Itís just a huge auditorium. If youíve never been there before, itís kind of cavernous. You go in there and you go, my God, I didnít know there was an auditorium this big in Stanford, but there is, and itís ours for that short period of time.
If you have a midterm conflict and you already sent me email Ė if you havenít already sent me email, you can go ahead and try, but I canít accommodate any more requests. I can hopefully just tell you when the alternate midterm is, but you will get an email from me this weekend letting you know when and where the alternate midterm is, so read your email this weekend. Itíll probably come some time in the wee hours of the night either on Saturday or Sunday, which would be the weekend, strangely enough. So watch your email for the alternate midterm.
If youíre an SAPD student, SAPD students have two options. If youíre a local SAPD student, you can come in for the exam, so just come on down, 7:00 p.m. to 8:30 p.m., Kresge Auditorium, October 30th. Take it along with everyone else, introduce yourself, come by, say hi. I always like to meet the SAPD students.
If youíre remote, because I know some of you are saying, not in the state of California, and it would kind of be a stretch to ask you to fly here just to take the midterm exam, you may take the exam remotely at your site. If you plan on taking the exam remotely at your site, you need to send me email, and in that email you need to let me know your name as well as your site administrator. Find out who your site administrator is if you do not know, because your site administrator will be administering the exam to you, and I need to know their email address.
So send me your name and email, which Iíll get when you send me email, but your site administratorís name and email so I can email them the exam and they can administer it to you. And if youíre a local student, go ahead and send me email, and just say youíre coming in locally, just so I know that youíre coming in locally and that way I can keep track of everyone.
But extremely important for most students, if youíre a remote student and you donít send me email, so I have no way of contacting your site administrator, I canít give you the midterm, and thatís real bad times for just more reasons than you can shake a stick at, but youíre certainly welcome to try.
And last but not least, same announcement as last time. There is a syllabus change, a very minor syllabus change, based on just moving the discussion of arrays up by one day. So if youíre sort of reading along in the book and you wanna know what to read for Monday, Chapter 11 on arrays is what weíll be covering on Monday, and if youíre not following along in the book, you should be following along in the book, but now you know.
All right, so with that said, I wanna do just a tiny little bit of wrap up on what we talked about, memory and this whole notion of pointers last time, and go into our next great topic. All right? So time for our next great topic.
Well we need to do a little bit of pointers first. So the first example is something that we talked about very briefly last time, but I wanna make sure everyoneís sort of on board with this. So if I have our friend, the point, that we talked about last time, which is just a class that stores two values, an x and a y that we pass into the constructor, when we do something like this Ė Iíll draw it sort of over on this board.
Now Iím gonna draw it in a Ė actually, Iíll draw it over here, and Iíll draw it in a way that we donít need to worry about all the memory addresses and overhead and all that stuff, because that sometimes makes the diagrams a little bit ugly, and so Iíll show you the very simple, stylized version of keeping track of the stack and the heap.
So over here is the heap, over here is the stack, and what weíre gonna do is say, hey, when we declare point p one before we have done this new, what we get is p one, which is basically just some box on the stack. What does it hold right now? Well, until we do this line, it holds nothing. It holds nothing that we know about, okay?
When we call this new, it says, hey, heap, get me some new memory for a point, and so the heap kind of goes over and goes, boink, hereís some memory for a point, and it calls the constructor and says, hey, constructor, put in the values one one. So if somewhere on the heap we have the values one and one for our little private x and our private y somewhere on the heap, and the value that new gives back, that we assigned to p one, is the address of this thing.
Remember, we donít really care about where in memory this thingís actually stored, and so sometimes, what we like to do is just keep track of addresses by pointer. So we know that this is just some memory address over here, where this particularly object is actually stored on the heap. Okay?
So now, if we do point p two Ė actually, let me not let Ė put the semicolon on yet. If we do point p two, what we get is, on the stack, we get some new space set aside for p two and, again, its beginning value is unknown.
Now we have a couple options. One thing we could do is say new point, and give it some x y location, in which case weíll get a new point on the heap and p two will point to that new point. We could do something funky like say, hey, p two equals p one. Well all thatís happened there is saying, take the value thatís in p one, which is a pointer over to this location on the heap, and set p two equal to that. So if this happens to be a memory location A A A E, this guy gets A A A E, which means, in our sort of stylistic representation, itís pointing to the same place. Okay? Are we sort of onboard with that? If youíre onboard with that, nod your head. Excellente.
All right. So now if we do p two dot move, and we tell it to move by an amount like three comma four, it says, well, in order to call the move method, I need to call the move method using the object p two. Where does the object p two live? It looks it up through the pointer and says, here, this is where you live. Call the move method with this particular object. So a path to this pointer to this location in memory, and it says, move three four, and as you saw with move last time, all move does is add those values to the respective x and y. So p x becomes four, p y becomes five, and now that move method is done. And, interestingly enough, what Iíve done is change not only p two, but also p one, because they were pointing to the same place in memory. They were the same actually point, and thatís the important thing to keep in mind.
If I set an object equal to another object like this, they are the same actual object. Thereís only one of those objects that lives somewhere, and I really have two things that are pointing, or what we really like to refer to as referring, to that object. So often times we refer to these things as references, okay?
Now what happens if I come along and say, point p three. I get p three over here on the stack, right? And again Ė Iíll write the p three over here so as not to interfere with the lines, and Iíll draw this line a little bit around p three so it kind of goes like that. It says, p three, I donít wanna interfere with you, Iím just gonna zigzag around.
P three, what value does it start with? I donít know. Itís not pointing to an object yet, because it hasnít been initialized to point to an object. It hasnít been initialized to point to a new object. And so if I come along and say, hey, you know what p three? I just wanna move you. Move to four comma five, because thatís where I hear the partyís at. Thatís where p one and p two are. Can you move yourself to four comma five? What happens when I do this?
Bad times, thatís what happens. What I get Ė well first of all, I get a social, because a whole bunch of people said it. But what I get is this thing. Who knows where itís pointing? As a matter of a fact, this pointer could, often times, be something we refer to as a null, which means itís not pointing to any particular object, in which case, when I try to do this, I get whatís called a null d reference. Anyone happen to see something called a null d reference while you were working on breakout? A few folks? Yeah, this is what you were getting.
You had some object here that wasnít actually pointing anywhere, and you were trying to call a method on it that says, hey, Iím trying to call the move method on p three and p three says, I got nothing for you, man. I got nothing here. Youíre trying to move something that doesnít exist, so youíre trying to dereference, which means go through the reference, itís a funky name for go through, we say d reference, something that doesnít exist, or maybe this is just Ė has some random value thatís pointing off somewhere into memory that you donít know about, which isnít actually an object. Okay?
So thatís what you wanna watch out for. This is real bad times if you actually happen to call a method on some object which doesnít really exist, okay?
Now the other thing thatís important about seeing these little pointers is the fact that Ė remember when we talked about parameter passing? And in the days of yore, we talked about parameter passing and we used to have this little thing where we said, hey, you know what? If you have something like an integer, or a double, or a char, or a Boolean, these are what we refer to as primitive types.
They were like hanging around, theyíre, you know, lower on the evolutionary ladder. Theyíre just what we referred to as the primitive types. When you pass primitive types as parameters, what you are getting is a copy of the value of the primitive type, okay? What does that mean?
It means, when I call some function, and I say, hey, function, Iím gonna pass to you a three, like in my move method over here I passed in a three, which is an integer, what actually happens when I make this method call is I pass a copy of the three, and so if in this move method I try to change this value around to something else, all Iím doing is changing the copy. Iím not changing the actual parameter that was passed in.
So if this wasnít a value Ė letís say I actually had some variables here like x and y, and up here I had int x and y, when I make this method call, I get copies of whatever values are in the boxes for x and y, and so if move tries to muck with x and y, all itís changing is the copy. Itís not changing the x and y out here, right? Thatís what we talked about a long time ago, and we talked about little Neron, who went off to France with his mom and the Mona Lisa, and he wanted to take a hacksaw to the Mona Lisa, but the Mona Lisa, he just got a copy, because they went to the gift shop. Yeah, primitive types, you go to the gift shop.
Now, something funky happens though when youíre dealing with objects, okay? So when youíre dealing with objects, they are not primitive types, they are object, and so when you make a method call where you pass some object along, what you are actually doing is you are passing the object Ė or, actually, what we refer to is the object reference. What does that actually mean?
What that means is, letís say I call Ė were to call some method over here, where I actually pass in a point. So letís say thereís some method over here like Ė well Iíll call it change zero, which is supposed to set a point to be zero, and I pass it, p one Ė and this is just some method that I wrote, and maybe the elements of a point are actually public, letís say, as opposed to private, so this function can actually access those things. What happens when I pass p one?
Well what happens when I pass p one to this change zero method or this change zero function is Iím passing where p one lives, so the parameter I actually pass is the address thatís in here. So if the address thatís in here is, letís say, the value a zero zero zero, I pass, as my parameter, a zero zero zero, which means what I have is a reference, because I have that pointer, to where p one really lives in memory, which means if this method decides that itís gonna muck around with p one and tell, hey, p one, move yourself to some other location, the values that itís gonna change when it makes method calls on the parameter thatís passed in is at this place in memory, because it knows where this place in memory is, right?
You wanna think about, when youíre passing objects, this is, as we talked about it before, sort of like the mafia. When you pass around objects, youíre talking to the mafia, and when you talk to the mafia, they know where you live, okay? They can come in and mess with you however they want. Theyíre not getting a copy of you to talk. You go to the mafia and youíre like, oh, Iím gonna send my clone along to the copy and Ė or my clone along to the mafia and theyíll just talk with him. No. When youíre gonna go talk to the like the Godfather or the Godmother, youíre not sending in your clone. Youíre going in yourself, right? And youíre like hey, Godfather, and heís like, you come here on the day of my daughterís wedding. Anyway, thatís a Ė anyone seen the movie the Godfather? Itís so good. If you havenít seen it, go see it, but we wonít talk about that right now.
What we talk about is the fact that, if they know where you live, any changes you make are not to a copy, and thatís a critical idea to know. This is what we refer to, up here, as pass by value, because what youíre getting is just a copy of the value. Youíre not getting the reference. This is what we actually refer to as passing by object reference. So Iíll just change the the here to a by, which means that when you pass objects around, youíre passing a reference to the object, you know where the object lives.
Hereís a little way you can think about it. So remember our story about little Neron, who goes to see the Mona Lisa? Think about it this way. When little Neron went to see the Mona Lisa Ė again, here is the Mona Lisa smiling, here is little Neron Ė bowlegged Neron, ponytail, chainsaw. When he wants to actually Ė if the Mona Lisa were just some integer, right, heís gonna go to the gift shop and heís gonna get copies.
But the Mona Lisa is actually something thatís really valuable, so what we do with the Monsa Lisa? Itís encapsulated in this big safe thatís an object, and so when we wanna say, send the Mona Lisa over to like the MoMA in New York, not that they would actually display it at the MoMA, but letís say we send it to the MoMA in New York, weíre sending the actual Mona Lisa. Weíre not sending a copy of the Mona Lisa, weíre sending the actual thing.
So then, in the MoMA in New York, Neron comes along and says, hey, you know what? Security is much more lax here. Iím just gonna chop this thing up. So he takes the chainsaw to the Mona Lisa and chops it up, and thatís the real Mona Lisa, so when weíre done with it being displayed at the MoMA, and it goes back to our friend the Louvre in Paris Ė so here it is in Paris, yeah, itís still sliced in half. Bad times. Major international incident, okay?
Donít let this happen to you. If youíre gonna mess with an object thatís passed around, know that youíre changing the actual object, okay?
So one thing you might say about this is, you said, hey, Neron, you were saying talking about Mona Lisa encapsulating that in an object, so if I have some integer, and I actually wanted to change it, could I create an object around an integer and then pass the object and allow someone else to change the integer inside that object, would that work?
Yeah, in fact, that would, and if youíre interested in doing that, thereís an example that does exactly that on Page 235 of the book. Just because itís important to memorize every single page of the book, but itís there. Okay? I just had to check. Yeah, itís 235. So just something you should know. So any questions about that?
All right so, last but not least, one other thing I should mention since weíre on the subject of saying, hey, why not take one of these primitive types and encapsulate it inside a class, it turns out Java actually has a bunch of classes already built in which are encapsulations of these data.
So for an int, there is something called Integer with a capital I and the full word, which is actually a class, that is a class that stores a single integer. The only unfortunate thing about this class is you would say, hey, now I can create integers and I can pass around an integer and change the integer, right? This class doesnít actually give you any methods to change the value, so it doesnít get you the effect you want. Weíll use them later on in the quarter for something different, but just so you know these exist. There are the double, and then thereís the class version, which is actually upper case double, so Java is case sensitive, and if you ever put upper case double, you would actually have been using the class version of it.
Similarly, with Boolean, thereís Boolean and thereís upper case Boolean, and then with char itís a little bit different. We have char over here, and here itís the full word, character, is the class. So these are sort of the class equivalent, these are the primitive equivalents. For everything weíre doing so far, unless you get told to use the class equivalent, just use the primitive equivalent and life will be good.
This is just kind of an artifact of programming language. Sometimes, in life, things just happen to happen this way, and you get two versions of something just because thatís the way life is, okay? But these class versions Ė remember, like strings? We said strings were immutable and you canít actually change the string in place, all you can do is create a new one. These classes are all also immutable. Once you create an integer and give it some initial value, you canít change that initial value.
If you wanna say, hey, I wanna take that value and add one, you need to create a new object of type integer, which has the old value plus one added to it, and you get a new object. So theyíre immutable in the same way strings are immutable. You create new ones. You canít change the value once youíve gotten an initial value. So, any questions about this, or any questions about this whole notion of pointers and references and passing the stuff around as parameters? Do you? Because, if not, itís time for out next great topic.
And our next great topic, itís something that really is a great topic in Computer Science, because itís something youíve been doing this whole time, and now itís time to lift up the covers and say, hey, you know what? There are some much more dangerous things you can do than youíve been doing right now. So, before, we sort of gave you the safety scissors, where it has like the rounded corners and theyíre like rubber. Remember safety scissors? They were fun. I liked safety scissors.
Now, basically, we take the safety scissors, we take them to the mill, we sharpen them up real sharp, we have you hold them up and run with them. Okay? So hereís where things get dangerous.
Files. Youíre going to learn how to read and create files as well, which means the opportunities to erase files or write over them, which is why things get dangerous, but itís really not that dangerous so long as youíre careful, right?
When youíre running with scissors, just point them down, and things will be Ė why people ran with scissors just made no sense to me, but Ė I really need to go cut this piece of paper! Come on, weíre all going. Itís the paper-cutting marathon.
All right, so files. What is a file? Youíve used files the whole time, right? When you created some program, like you had My Program dot Java, that was just stored in some file somewhere, and you Ė when you write a paper in your favorite Microsoft Ė your favorite Microsoft Ė your favorite Word Processor, which may or may not be a Microsoft product, youíre creating a file. And, in Java, you should be able to create files and read files as well, so thatís something weíre gonna do, and the first thing weíre gonna thing about is reading files.
Now the files weíre gonna think about reading are not necessarily Java files. Weíre actually gonna think about just plain text files, and often times youíll see these things as Ė itíll have some name followed by a dot followed by txt, which is kind of the extension that means text, but thatís what weíre gonna deal with, is just files that contain a bunch of characters, without any of the characters being like special meaning characters or anything like that.
So the way we think about a file Ė let me just draw a file up here, because life is cheap. As a matter of a fact, Iíll show you a little file on the computer. Wake up. Donít worry, itíll come back. Itíll just take a moment. Wake up little guy. Yeah, itís time for your starring role. Hereís a file. See I just want it to say, A students rock the house, there can be no doubt about it. Doubt about it. Doubt it. I put two doubts in there, I donít know why, I just did. All right.
Itís one of those little things, like Springtime in the Paris. Remember that little puzzle? No. All right. Letís not worry about it. When something is at the beginning and the ending of the line, the human brain is just likely to convolve it and think there is only one there. Random psychology for the day. Thank you. Letís move on.
Hereís a little file. Itís a text file. It just contains a bunch of lines of characters. The way we like to think about files is that weíre gonna process a file one line at a time, and we read files sequentially which means we tell the computer, hey, here is the file that I wanna start reading. It says, okay, Iím ready to read the file, and it starts at the very beginning of that file, and then I will ask the computer line by line, give me the next line of the file, and itíll give it to you as a string, and you can do whatever you want with that string, and then when you go to read the next line of the file, youíll get the next line.
So first youíll get cs106 a students, then next time you ask for a line youíll get rock the house, then thereíll be there can be no doubt, then youíll get, doubt it, then youíll get some indication that youíve reached the end of the file, okay? So what does that look like, all right, and how do you actually do this?
So youíre gonna be doing this for assignment No. 4, hangman, so itís a good thing to know. So first thing you wanna do is whatís referred to as opening the file. Opening the file basically means youíre gonna associate some object Ė youíre gonna create some object, which is actually something we referred to as a buffered reader, and youíll see an example of that in just a second. Youíre gonna have some object that essentially corresponds to some actual file on your disk. So when you open a file, what youíre doing is saying, Iím going to have some object Iím going to create, and when I refer to that object, Iím actually gonna tell you that itís referring to some particular file thatís on my disk right now. So thatís opening the file, is creating this correspondence.
Then the second thing you do is you basically read the file, and thereís multiple ways of reading the file, but weíre gonna focus on reading a file line by line until weíve read as much of the file as we want, usually the whole file, and then the third thing you need to is, because you open the file, you need to close the file, which basically cuts this correspondence between the object and the file. It says, okay, Iím done with that file now. This object is no longer referring to that file. This object is kind of, Iím gonna be done with it.
So, in order to use some of this function Ė Iíll show you the code in just a second Ė thereís a particular package you need to import, called the Java dot IO, which stands for input output, dot star. So at the top of your program, youíll have an import, then it has Java dot, just the letters IO dot star semicolon, and that will give you all sort of the file stuff.
So how do we actually do one of these things? Weíre gonna open a file, weíre gonna read its contents, and weíre gonna close it. Itís time to write a little code.
So first thing weíre gonna do is weíre gonna create on of our friends, the buffered reader. So weíre gonna have some object thatís of type buffered reader, and this is just a class that exists in Java dot IO. Thatís why you import that package, and youíre gonna be able to refer to objects of this type.
So buffered reader, Iíll just call it rd, for reader, for short, and what Iím gonna set that to is a new buffered reader, so this going to be a new buffered reader, and the new buffered reader needs some parameter, and hereís where things get funky. The type of parameter itís going to take is something called a file reader. Thatís a special kind of object that knows how to attach itself to an actual file on disk, but I need to create one of those, so hereís the idiom for how I create it. The idiom is just sort of the pattern youíll always see in programs. I say new buffered reader, and the parameter that I passed to my new buffered reader is a new file reader, upper case R, new file reader, and the parameter that I give to new file reader is the name of the file on the disk.
So if the file on the disk is called, like in this example, students dot txt, Iíd actually give it here as a string, students dot txt Ė I need a space for a few extra params there, so let me write that a little bit smaller. Students dot txt. Thatís the end of the string. Then I have this param to close that param, and another param to close that param.
So what it does, it says create a new file reader, which basically is an object that associates with a particular file on the disk, and that object is what gets passed into a buffered reader, and the buffered reader is what youíre gonna ask to get line by line. So youíre gonna say, hey, buffered reader, give me a new line, and itís gonna go say, hey, file reader, get the line from that file, and get it back and give it to you. Okay?
So this is just the standard idiom you always see and the way that itís written, and you can put any string in here you want. As a matter of a fact, you can put in a string variable if you want.
Now after youíve created that, how do you actually read from the file? So letís have a while loop that will read in every line of the file, so weíll have a while true loop, because weíre gonna keep reading until we reach the end of the file, and the way we read this is, weíre gonna read the file line by line, and each line is just a string. So I have string line, I tell the buffered reader, this rd object, read line, which kind of looks familiar to you because it sort of looks like reading a line from the user, but in fact, youíre passing the read line message to the rd object, which means get me a line from the file. Which file? This file that I created the correspondence with over here, okay?
Now this will read line by line. Every time I call rd read line, Iím gonna get in some Ė the next line from the file. What do I get when I reach the end of the file? And this is the crucial thing. One thing you might is, hey, do you get an empty string? Like do you get double quote double quote? No, in fact, I donít, because my file could actually create Ė contain empty lines, and I donít wanna confuse an empty line in a file with the fact that Iíve reached the end of the file.
So the way I signal reaching the file is Ė remember a string is just an object. How do I refer to an object that doesnít exist? Null. So what read line gives me back, if I try to read a line past the end of the file, is it gives me back a null. It says, hey, there is no string here for you to read, and the way Iím gonna indicate that to you is to give you back a null. So I can check that. If line is equal equal to null, that means Iíve reached the end of the file, and so Iím just gonna break out Ė and hereís my little loop and a half. Iím gonna break out of this while loop.
And if I got a valid line, Iím just gonna print it to the screen. So all this code is gonna do is take some file, read it line by line and print every line to the screen, and since every line is just a string, I can just do a println to Ė of line, and that will write it out to the screen. Okay? So any questions about this?
Now thereís one thing I havenít done yet, right? In my steps over here, Iíve opened the file, because I created the buffered reader, Iíve read the file. Now I need to close the file. So after Iíve done reading all the lines from the file Ė let me move my brace up a little bit to give myself room for this. I just say rd. I refer to the object, and then I say close, and thereís no parameters there, and that kind of says, Iím done with you. Thanks. Thanks buffered reader, you did good work, you got me all the lines of the file and now Iím done with you, so Iím just gonna close it off. Okay? Question?
Instructor (Mehran Sahami): Yeah, read line keeps track of where it is in the file itself, so every time you read a line, itís automatically keeping track of where it is in the file and will go to the next line. Nice catch.
So now thereís another thing that happens, and youíre like, good times, Iím all ready to read files, right? Almost. The one extra thing you need to know about Ė and this is the part where itís just kind of one of the stickinesses of programming, is what happens when bad things happen to good people. Youíre like, what does that mean man?
Well what that means is, letís say I come along and I say, hey, buffered reader, open up students dot txt, and some evil person came along and deleted your students dot txt file, and so this guyís trying to create a correspondence between this buffered reader and students dot txt, and it says, there is no students dot txt. I got nothing here. What am I gonna do? It needs to signal that back to you somehow, and the way it signals that back to you is it says, whoa, this is just something that I didnít expect at all, and it gives you something called an exception. Okay?
So what is an exception, and whatís involved with actually getting an exception and dealing with exceptions, okay? So the idea here is what we refer to when an exception happens, right? Like when this guy tries to look up this file and the file doesnít exist, is Ė the term we use is it throws an exception. Thatís just life in the city, all right? So letís say Iím the buffered file reader, and Iím trying to read students dot txt, and the students dot txt doesnít exist. So I say, thatís an exception. What am I gonna do with the exception? Itís gonna throw the exception. All right?
So someone gets the exception. You got the exception. You donít just leave it there, you got the exception man. All right. What are you gonna do with the exception?
Student:I caught it.
Instructor (Mehran Sahami): You caught it, thatís important. Hold on to it for the time being, okay? Because itís important, right? Thatís a valuable commodity, so just hold that exception, hold that thought, okay?
So when an exception gets thrown, there has to be some notion of catching the exception, hopefully, and if no one catches the exception, your program is gonna stop executive, because if thereís no one there to catch the exception, that exception is just gonna sort of go up all possible functions in your program and say, hey, is there anyone here to catch me? Thereís no one here to catch me. Okay, your programís done, because no one caught me and Iím a pretty important thing to catch, okay? Thatís why I needed you to catch it.
Iíll set you up for catching it, because I know it took a little effort, but itís important to catch it. Just hold onto it for the time being, okay?
So how do you actually catch an exception? Or how do you actually tell the computer, Iím going to do something that may involve an exception. So you actually need to set it up and let the computer know, hey, Iím gonna do something that may involve an exception. The way you say that is you say try. I want you to try something. This thing may throw an exception, so be prepared, but I want you to try it.
Inside here you have your code for file access, and thatís whatever youíre doing with the file, trying to create a new buffered reader with the file, reading in lines one by one or closing a file. Any time youíre trying to do something that involves a file access, you need to put it inside this thing called a try that says, hey, Iím gonna try this out, it may throw and exception.
Now what happens if it does throw an exception? You have something over here where you write catch, and what youíre gonna catch, in this case, is something called an IO exception, because itís an exception that happens when youíre trying to do IO, or input output, and thereís this ex thing which is actually the exception. Itís that little envelope that you actually catch in your hands.
And then you have some code here which is how to deal with the exception, okay? So if you are doing something inside here and some place, as soon as you get to it, says, whoa, something bad happened, exception, it does not execute any more of the remaining statements inside this block for try. As soon as it gets an exception inside here, it says, whoa. Hereís an exception. It throws it. Where are you gonna catch it? Youíre gonna catch it here, which means as soon as an exception gets thrown even in the middle somewhere here, the rest of this does not get executed and it comes over here to this code to deal with catching the exception.
If it gets through all of the code where you said, hey, Iím gonna try something dangerous, it gets through all of it and it doesnít throw an exception, this code down here is not executed. So this code down here is only executed if an exception was thrown, okay?
So what does that actually look like, okay? Letís write some code that deals with trying to catch an exception. Just keep holding it. Itís a good time. Weíre kind of running our program in slow motion. Itís kind of like, you got the exception, and normally youíd be like, catch, here Iím gonna do something with it. Here weíre kind of like Ė weíre taking our time. Itís mellow, itís good. Here, Iíll give you a little more candy just to keep you awake with the exception.
All right. You never thought just by like sitting there you could just accumulate food. All right, so we have private. Weíre gonna return a buffered reader, so this a function Ė or a method, weíre gonna write, letís say, private method inside some class. Itís gonna return a buffered reader, and what weíll this is weíll call this open file, so the name of the method Ė let me make this all a little bit smaller, so I can fit it on one line.
Private buffered reader Ė and what itís gonna get past is basically some string which is a prompt to ask the user for the name of the file to open. So thatís a common thing you wanna do. You ask the user, hey, what file do you actually wanna open for reading?
So how might I do that? Iím gonna start off Ė I wanna return one of these buffered readers, which means Iím gonna need to have a buffered reader object in here at some point. So Iím gonna declare a buffered reader as a local variable rd, and Iím gonna set it initially to be null, which means I created the buffered reader Ė at least, I created a pointer for it, a reference for it. I have not actually created the object yet, so I canít say I actually pass Ė make any method calls on rd yet. Iíve just sort of created the local variable. Iím gonna actually create the object in just a second.
Iím gonna have a while loop here and say, while rd is equal equal to null. So I know that thatís gonna execute the first time through, because I said it equaled to null to begin with, and then what Iím gonna do inside here, so I have a brace there, is Iím gonna say, hey, Iím gonna try something that may be dangerous.
So what I wanna try doing is, Iím going to ask the user to give me the name of the file. So Iím gonna have string name equals read line, and Iíll pass it whatever prompt was given to me as a parameter, right? So Iím just asking Ė all Iím doing here is asking the user to enter the name of the file, right? And whatever prompt I write on the screen is Ė excuse me, just whatever was passed in here. So it might have been something like, please enter file was the string. So Iíll write out please enter file and ask the user for the filename.
Now here comes the dangerous part. I wanna create the buffered reader. So I say rd equals new buffered reader, and the parameter Iím gonna pass to a buffered reader is new file reader, and the parameter Iím gonna give to the file reader is whatever file name the user gave me. So this is just name.
So what this is gonna try to do is, whatever the user gave me, itís going to try to create one of these new buffered reader objects that corresponds to the file with that name thatís actually on disk. If that file exists and it creates the correspondence, life is good. rd actually is now pointing to some valid object which is a buffered reader. If that file does not exist, Iíve thrown an exception. I say bad times. The user mistyped something or they gave me the name of a file that doesnít exist. Hereís an exception, buddy. Itís not there, I canít create the correspondence.
If that exception thrown -- right, I never created a new object, which means I never returned a value assigned to rd, which means rd still has the value null. Thatís an important thing, because if I do this try, and the fileís not there, Iím gonna catch this IO exception Ė exception ex, and what Iím gonna do when I catch that exception, Iím not actually gonna do anything with the exception, the parameter ex thatís passed in. All Iím gonna do is just write a println to the person saying, like, bad file, and then Iím gonna have a closed param, and Ė closed param here, or a closed brace for the while loop, so this brace corresponds to while loop, and if all of this works out, Iíll just Ė Iíll write it right over here on the side. I will return rd. That line would go right down here.
So what does this code do? It says, create the space for an object, or create one of these pointers to an object, but set it to be null. Itís not a point Ė itís not pointing to a real object yet, and while it remains null, ask the user for a line, try to open up a buffered reader to that file.
If this works, life is good, I donít execute the catch portion, and rd now has a non-null value, because itís actually a valid buffer reader object, and so when I try to do this while loop again, rd is no longer equal to null which means Iím done with the loop and I will return this object that I just created, which is actually this object that is a valid correspondence to a file. So thatís a very convenient way, in one method, to encapsulate all the work of opening up a file and getting a valid reference to a buffered reader that refers to that file.
If I tried to create this file reader and this file, for whatever reason, did not exist, an exception gets thrown. If an exception gets thrown, execution doesnít complete at this line, so rd never gets assigned a new value, and it immediately goes to the catch and says, hey, here is the exception. I couldnít find the file. What does the exception catcher do? It says, hey, bad file, buddy. And then itís done. It just reaches the end of the catch part, and execution continues. So it comes to Ė the end of the while loop comes back up here and rd still has the value null, so it asks the user, hey, enter a file again, and tries to do this whole process again, and youíll get out of this loop when buffered reader actually gets a valid object.
Instructor (Mehran Sahami): Yeah, thatís a good point. What you wanna do is, when youíre trying something dangerous, you donít wanna just tell your whole program Ė you donít wanna say, hey, program, let me put everything inside a try, because Iím gonna be doing all this dangerous stuff, and I donít know when Iím gonna do it. I might do a little here and a little over there, so put it all inside this huge try block. Thatís really bad style.
What you really wanna do is only do as little as possible in the try, and say, hey, Iím about to do something dangerous. Let me encapsulate that in one of these things thatís a try catch Ė we refer to it as a try catch block, because we have a try and a catch, and as soon as Iím done with the dangerous part, then let me get out of that try block, because I need to know that, okay, now Iím not doing dangerous stuff anymore, and the programmer needs to know that when they see the files. They need to understand when youíre doing dangerous stuff versus not, okay? So any questions about that, this notion of throwing an exception?
All right. So now hereís the interesting that happens, okay? Sometimes when an exception gets thrown, you know what you wanna do, like, you wanna say, hey, that file didnít exist. I write out bad file, and I keep executing. Sometimes you get an exception and you have no idea what to do. You try to Ė you created this correspondence to students. That works just fine. And you start reading lines from the file, and itís just fine, but before you get to the end of the file, what happens?
Your roommate comes along and deleted the file, or like, beats your computer on the head and your disk crashes or whatever and your programís still executing, but your disk is no longer working. This has actually happened before. You try to say, hey, buffered reader, get me a line, and it says Ė it says, no more line. Like, I thought I had the file and everything, but thereís no more line. I donít know what to do. What does it do? It throws an exception.
Sometimes when it throws an exception, what are you gonna do here, right? You just tried to read a line and youíre like, what, the line doesnít exist? But the file existed, and now youíre telling me the line doesnít exist? What am I gonna do? Sometimes you donít know what youíre gonna do, and when you donít know what youíre gonna do, what you do is you say, hey, you know that exception that got thrown to me? Iím just gonna keep throwing it.
So throw the exception back to me. And somewhere Ė now I donít feel so bad about missing you the first time. Someone gets the exception, right? And if I didnít get it, like you throw it to me and Iím just like, what exception, right, and Iím your program. The program just died. Someone comes along and beats me on the head, and says, hey, you didnít catch the exception, you stop executing. But sometimes like, someone gets it, and theyíre like, hey, I know what to do with the exception. Itís all good. All right? And they get something out, and theyíre like, yeah, really all the exception was was some clothing I needed you to wear. You didnít know how to wear it. Iím sorry, youíre not quite as stylish as I am.
So I know how to do with the exception. Once I know how to deal with the exception, Iím done with the exception and I kind of keep executing from where Iím at, but I appreciate you catching the exception to begin with, and if you didnít know what to do with it, you just keep throwing it along its way, okay?
So one more time, just for throwing it. And to the people around you, for getting pelted with candy. All right. So what does this actually look like in code? Okay. So letís look at a little code. Come on little guy. Wake up. Sleepy Mac, sleepy Mac. So what does this actually look like in code?
Whatís gonna happen is, here is our little function that we just wrote over there, our method, return to buffered reader. So this is all the same code. It creates a buffered reader thatís null. While itís null, it asked the user for a file name, it tries to create a new buffered reader with that file name. If it doesnít exist, it says, nice try, punk. That file doesnít exist. And it asks again, all right?
So this is just fine. This is what we wrote. This is an exception that we know how to deal with. We donít actually use this ex portion. You donít need to care about that or whatever. You just say, yeah, I know the file didnít exist, so Iíll write out a message to the user and keep executing.
Now down here Ė donít worry about the set font, thatís just making the font bigger. Iím gonna say, hey, Iím gonna call my open file Ė this is basically a passively aggressive program. It asks you real nice, please enter the file, and if you get it wrong, nice try punk. That file doesnít exist. And then it says, please enter file name, all right? Weíll make no more comments about passive aggressive behavior.
But it calls open file, it passes in this prompt, and what itís guaranteed to get back is an rd object that is a valid file, right? Because if it didnít get a valid file, it just keeps looping here until it got a valid object that it could actually correspond how it corresponded to the file. And youíre like, thatís great. Now I need to read the file.
Reading the file is a dangerous thing to do, because Iím referring to this file and I donít know if something bad will suddenly happen and the file will go away, so I put this inside another one of these try catch blocks. So not only do I have a try catch block for making the Ė for opening the file, every time I try to read the file or potentially close the file, I need to have one of these too.
So this guy comes along and says, okay, Iím gonna have a while true loop and read all the lines of the file, kind of like Neron showed me before. So Iíll have this variable line that I just read a line from the file. If that line is null, then I know Iíve reached the end of the file, so Iím done, and I break out of the while loop and I will come here and close the file. Always remember to close your file. Itís just good practice. If the line is not null, Iím just gonna write it out to the screen, and Iíll say, read line, and Iíll write out, inside little brackets just so itís clear what the beginning and ending of the line were, the line that I write in, okay? And Iíll just keep doing this, and when Iím done, and I donít get an exception, I close the file, and I will skip over this catch portion and just keep executing, which means my programís done.
If, however, while Iím reading the file, one of my Ė I say, read line, and it just doesnít exist, I come over here to the exception, and I say, hey, I got this IO exception. I donít know how to deal with that, right? I donít know how to deal with the fact that I just read a line and it doesnít exist, so Iím just gonna throw an exception to someone else.
So what I do inside here is, I will throw a new exception, and the exception you will always throw, if you donít know which exception to throw, which is most of the time, you wonít know which exception to throw, is something that we call the error exception. So you say, hey, I got an exception, I donít know how to deal with it, maybe someone else who was trying to access me put me inside a try catch block, so Iím gonna throw an exception up to them and see if they can catch the exception, and the exception Iím gonna throw is an error exception, and error Ė when you throw an exception, it has a parameter, and thatís just the exception object that youíre throwing along.
You actually got some exception object past you when the exception was thrown. You didnít wanna look inside, you didnít wanna deal with it, and as a matter of a fact, you donít need to look inside or deal with it. All youíre gonna do is just continue to pass that exception object up to the person who may have called you, okay?
So, when you throw an exception, execution would stop in the method that youíre at, at that point where you throw the exception the method will end, and it will throw an exception up to whoever called this method, okay? Unless this happens to all be inside some other catch block inside here, in which case youíll catch the exception yourself, but if youíre not trying to catch the exception yourself, itíll just get passed up and someone else will catch it, okay?
So any questions about this? Here we know how to deal with the exception, here we donít know how to deal with the exception, and if you wanna actually be able to pass an error exception, thatís something thatís defined in this thing called ACMU till. So itís an exception thatís defined in the ACM libraries. You should import ACM dot u till dot star to be able to throw one of these error exceptions, okay?
So this is Ė let me just run this program, just so you can actually see that it works. This is another file example. And then, I will show you something thatís extremely cool, which is basically, in 10 lines of code, you can copy files, doing it all in Java. And youíre like, yeah, man, but I can copy files in like four clicks of my mouse. Yeah, what if I just took your mouse and just busted it? Right? Then what would you do. And youíre like, yeah, then Iíd write a Java program to copy a file. Donít force me to bust your mouse. One of my other mice busted last night, and it was just a harrowing experience.
So I wanna enter the file name, and I say, the file name is Ė what was the called? Was it called Stanford dot txt? No. It was called students. I keep pressing the A. Students. Yeah, I canít even type anymore. Wasnít it called students? No, it was called students dot txt. I forget the students dot txt. And then when it finally gets a valid file and creates the correspondence, notice that youíre reading the lines from the file one by one and it just them in strings and itís printing them out, okay? Any questions about that?
So, besides reading files, sometimes in life you also wanna be able to write files. So hereís the quicky way to be able to write a file, okay? Itís similar Ė very similar, itís actually Ė writing a file is even easier than reading one, if you can believe that, and youíre like, but man, reading one is pretty easy. Yeah, it is, and writing oneís even easier, so itís just that much cooler, and if I can find my chalk, itíll be even that much cooler. Here it is.
What youíre gonna do is, guess what? Youíre gonna open a file to write. This is something Ė rather than using a buffered reader, we call it a print writer. You will create a print writer object. Two, you will write to the file, unlike reading from the file where you use read lin, itís very easy to write to a file. You just do printlns to the file. You use println, but youíre actually gonna be passing println to some object here. What object? Your print writer object. And the same ways youíve used a println to write on the screen, you can use it exactly the same way to write to a file, and when you are done, you will close the file. That looks real familiar, right? So letís actually see what that looks like in code.
So what Iím gonna show you is a little program that copies a file, line by line. So, once again, here is the exact same function we wrote before to open a file for reading, so this has our buffered reader stuff, and our little while loop, and keeps asking for file names until we read the file, so itís exactly the same code. Weíre just reusing the code. Thatís part of the beauty of code reuse, right?
What weíre gonna do here is weíre gonna open a file by asking the user to enter a file name, and this is the file thatís going to be our reader. So our object is rd. Now weíre going to create a file that is a Ė or a object, which is a writer. So weíre going to try, because weíre gonna do something dangerous.
Creating a file is dangerous, or writing a file is just as dangerous, as reading one. As a matter of a fact, in some sense, in a more esoteric way, it is more dangerous. Why is it more dangerous? Because, if you try to tell the computer, write to a file which already exists, whatís it gonna do? You might say, will it tell you that it already exists? Will it try to give you a different file name? No. Itíll go smash the file that exists there to bits, and write a brand new file. Which means, yeah, if youíre overwriting students dot txt, not a big deal. If youíre overwriting your word processor, big deal. Be careful what filenames you give when you are writing, because if that filename already exists, it will get rid of the one thatís already there and overwrite it with a new one, which is whatever you happen to write into it, okay?
So print writer. Weíre gonna create a new writer, and we want to, inside a print writer, just like we had this little thingy up here where we had a buffered reader and a buffered reader used a file reader over here, when we create a print writer Ė and this is all in Chapter 12 of the book, so you donít need to worry about scribbling this down quickly Ė a print writer, you say new file writer is the object you create and pass to a print writer, and you give it a filename.
Here Iíve Ė you could have given it like a string variable or whatever. Here Iíve just put in, directly, copy dot txt, so the thing Iím gonna create is the file called copy dot txt. All your files need to be in the same project as your code, so thatís where our new files will get created. Thatís where, when it looks to read a file, thatís where itís gonna look, is that same file that has your project.
So I have a while true loop. What am I gonna do in my while true loop? Iím gonna read, one line at a time, from my input file, from my reader. If my reader has no more lines, I get a null and I say, hey, Iím done reading. Iím gonna break out of the loop. If Iím not done reading, Iíve just gotten a line, Iím gonna write that line to the screen using println.
So println, without any object over here, writes to the console, because this is a println that is being called on the console program, and it writes to the console.
When I do wr dot println, thatís sending println to the write Ė the print writer object, and itís writing out the line. So itís saying, hereís this line. Hey, print writer, write this out to the file that you correspond to it. It says, okay, Iíll go write it in copy dot txt. And I keep looping like this. I get a new line. If itís not the end of the file, then I write it to the screen and I write it to the file. If I go through this whole while loop, and finish off everything, so I finish the whole file, I get to where line equals null, I say, hey, Iím done reading the file, so close the file to read. Iím also done writing the file, so I tell the writing file, the print writer, to close itself.
And this whole time, if something bad happens and I get an exception, I catch the exception and say, I donít know what to do with it, Iím just gonna throw it to someone else. Okay? And thatís the whole program. Thatís all the code you need to copy a file. So letís run this and just make sure it actually works.
Operation in progress. And just to show you that Iím not lying Ė let me cancel this for a second. Weíll open up some folders. Notice no copy dot txt in here. Hereís the little project file that I have, okay? Thereís my copy file class and my copy file dot Java file. Hereís my students dot txt file. No copy dot txt file. Now, magic. All right, we run. See, I had to tell you that, because I could have just cheated. I couldíve been Ė I just typed up the copy dot txt file.
Running, running, running. Come on, you can do it, in your glowing blue. I love the glowing blue. Itís fun. Copy file. Please enter file name. Students dot txt. Iíll spare you the incorrect files name. So itís copy Ė it says copying line. It writes out all these lines to the screen. Letís see if it actually exists. Copy dot txt. Itís warm, itís fuzzy, itís fun.
Now if you look over here, just wondering, you might look in your project and say, hey, I donít see. I thought this shows me everything in my folder. I donít see copy dot txt show up here. Yeah, you go up here, you right click, you pick refresh. Copy dot txt. And there it is. Looks identical to students dot txt. There you. All right, any questions? Then I will see you on Monday.
[End of Audio]
Duration: 51 minutes