COMP1406 Tutorial 11

Size: px
Start display at page:

Download "COMP1406 Tutorial 11"

Transcription

1 COMP1406 Tutorial 11 Objectives: To gain more practice handling Exceptions. To create your own Exceptions. To practice reading and writing binary files. To practice reading and writing text files. To practice reading and writing object files. To complete our DVDCollection App so that it can save and load DVDCollections to/from a file. Getting Started: Download the Tutorial 11.zip file from the CULearn website. Place the Tutorial 11.zip file somewhere that you can unzip it such as the Z drive in the labs. Select it and unzip it by selecting the file and then rightclicking and selecting Extract All from the popup menu. From the dialog box that appears, click Extract. It should by default, extract to the same folder that contains the zipped file. To open the project in IntelliJ, select Open from the File menu. Select the Tutorial 11 folder that is inside of the Tutorial 11 folder that you unzipped. MAKE SURE THAT YOU SELECT THE ONE INSIDE OF THE OTHER ONE (i.e., the inner one). The project should be loaded along with all of its original source files. Expand the project by clicking the triangle on its left. Click on the src subfolder. The code provided in this tutorial contains the solutions from Tutorial 4 which pertained to the Game that we simulated with various movable and stationary objects such as Player, Ball, Trap, Wall and Prize. It also contains the completed code from Tutorial 3 which pertained to Customer, Store and Mall classes. We will make use of these throughout this tutorial. Tutorial Problems: 1) Recall these classes GameObject MovableObject Player Ball StationaryObject Wall Trap Prize Game GameTestProgram GameBoard GameBoardTestProgram 1

2 Now we will add code that will generate a CollisionException when a Player collides with a wall. Of course, your code should attempt to prevent the Player from colliding with a wall, but in the off-chance that there is a bug in your code or that something unexpected occurs in the game, your player may end up colliding with the wall. Create and compile a CollisionException class as follows: public class CollisionException extends Exception { public CollisionException() { super("player collided with wall!"); Note that any new exceptions that you define must extend the Exception class or one of its subclasses. Once this code is saved and compiled, you are able to generate such an exception. Copy and then complete the code (i.e., it is not finished so you have to write it) for the following method in the Wall class: public boolean contains(point2d p) { // return true if p.x is in the range from "this.location.x to // (this.location.x+this.width-1)" and if p.y is in the range from // "this.location.y to (this.location.y+this.height-1)" // otherwise return false Add the following methods to the Game class so that we can get the Players and the Walls from the Game: public ArrayList<Player> getplayers() { ArrayList<Player> result = new ArrayList<Player>(); for (GameObject g: gameobjects) { if (g instanceof Player) result.add((player)g); return result; public ArrayList<Wall> getwalls() { ArrayList<Wall> result = new ArrayList<Wall>(); for (GameObject g: gameobjects) { if (g instanceof Wall) result.add((wall)g); return result; Append the following piece of code to the end of the updateobjects() method in the Game class which will compare all players with all walls to see if a collision occurs and will then throw our newly defined exception if it has indeed occurred: ArrayList<Player> ArrayList<Wall> players = getplayers(); walls = getwalls(); for (Wall w: walls) { for (Player p: players) { if (w.contains(p.location)) throw new CollisionException(); 2

3 The code will no longer compile. You should see an error stating: Unhandled exception: CollisionException. JAVA is telling us that we need to tell everyone that this updateobjects() method may now generate a CollisionException. Add an appropriate throws clause to the method definition as follows and then re-compile: public void updateobjects() throws CollisionException { The GameTestProgram and GameBoardTestProgram will both generate the same compile error because we are calling the updateobjects() method from here and we now must decide what to do when the exception is generated. For now, we are not sure what to do and we just want to see if we can generate our exception. So, to simply satisfy the compiler for now, add throws CollisionException to the main methods as follows, and then re-compile: public static void main(string args[]) throws CollisionException { Run the GameTestProgram. You should see the exception generated as follows (although your code's line numbers may differ): Exception in thread "main" CollisionException: Player collided with wall! at Game.updateObjects(Game.java:43) at GameTestProgram.main(GameTestProgram.java:53) at com.intellij.rt.execution.application.appmain.main(appmain.java:144) Congratulations you have just thrown a brand new exception. Notice that it occurs right where we threw it from the updateobjects() method in the Game class. Run the GameBoardTestProgram. You should see the exception occur just before the Player collides with the wall above him/her: #################### # $ # # # # # ########### # # ##### $ # # ^ # # # # # # # # # # # O# # $ # # # #################### Exception in thread "main" CollisionException: Player collided with wall! at Game.updateObjects(Game.java:43) at GameBoardTestProgram.main(GameBoardTestProgram.java:40) at com.intellij.rt.execution.application.appmain.main(appmain.java:144) 2) Now we need to catch and handle our exception properly. First, let us catch it. But where do we catch it? Recall that we have added some throws clauses to our methods and eventually the main method threw the exception and the Java Virtual Machine caught it, and hence stopped the program. 3

4 Change the following code from the main method in GameBoardTestProgram: into this: for (int i=0; i<15; i++) { g.updateobjects(); g.displayboard(); System.out.println(" "); for (int i=0; i<15; i++) { g.displayboard(); System.out.println(" "); g.updateobjects(); catch (CollisionException e) { // do nothing Remove the throws CollisionException clause that we added from the main method's definition and then re-run the code. Your program should run to completion because we caught the exception and ignored it. Let's see how many times the exception actually occurred. Add the following line inside the catch block, then re-run the code again: e.printstacktrace(); Scroll through the program output. Did you see how many times the exception occurred? I think you will notice it occurred 2 times, so the Player hit 2 walls as it moved (because the player does not stop when it hits the walls, it goes right through them). Obviously in a real game this would be serious. For now, let us simply stop the player when it hits a wall. We do this by setting its speed to 0. So we need to add the following to the catch block instead of printing the stack trace: System.out.println("*** " + e.getmessage() + " setting speed to 0"); player.speed = 0; Re-run the code. Notice that the player no longer goes through the wall. You may also notice that the exception occurs a LOT more now! What is going on? Do you understand? Print out the player's location from within the catch block. Think about it. Ask the TA if you do not understand why the exception occurs a lot now. 3) There are some bad things about the code. First of all, we are catching the exception in the wrong spot. Notice that our catch block "assumes" that it was the Player object stored in the player variable that collided because it sets that player's speed to 0. However, if any other Player collided with a wall, we would be setting the speed of the wrong Player. Can we fix this? Yes. There are many ways to accomplish this. One interesting way is to allow the CollisionException to store the Player that caused it. Then we can access this from our catch block. Looking to the future, we may wish to do something similar for Ball objects and perhaps any MovableObject. So let's allow any MovableObject to be a cause of the exception. Add an attribute (i.e., instance variable) to the CollisionException class: MovableObject source; 4

5 Then allow this to be set by the constructor by changing it as follows: public CollisionException(MovableObject s) { super(s + " collided with wall!"); source = s; Go back to the updateobjects() method in the Game class and pass in (to the call to the CollisionException constructor) the Player who generated the exception. Finally, in the catch block of the GameBoardTestProgram, replace player with e.source. The code should compile and still run. It seems that we did not do much, but we did clean up the code and allow the exception to keep track of any MovableObject that collides. 4) Let's eliminate the problem that caused the exception to occur so many times. Hopefully by now you realize that the exception kept occurring because the player was "stuck" on the wall. You will have to somehow "undo" the player's last forward movement. Since we are already keeping track of the previouslocation of the player, we can simply restore it when a collision occurs. Make the appropriate changes and then re-run your GameBoardTestProgram to make sure that the exception occurs only once. The exception message should appear after the 6th board is displayed not after the last displayed board as before. 5) We will now switch over to our Customer/Store example. Run the StoreTestProgram to make sure that it works. Also, create, save and compile the following test program: public class CustomerTestProgram { public static void main(string args[]) { Customer c1 = new Customer("Amie", 14, 'F', 100); Customer c2 = new Customer("Brad", 15, 'M', 0); Recall that we can create a DataOutputStream that allows us to output primitive types to a file as follows: DataOutputStream out = new DataOutputStream(new FileOutputStream("customer1.txt")); out.writeutf(c1.getname()); // UTF is short for "Unicode Text Format" out.writeint(c1.getage()); out.close(); Add such code to the CustomerTestProgram so that the first customer Amie is saved to a file called customer1.txt and Brad is saved to a file called customer2.txt. You will need to write all 5 attributes for each person. This will require you to add a getmoney() method in the Customer class. You will need to import java.io.*; and don't forget to close the files when you are done using the close() method. The code that you write, may not compile likely, you will get some errors indicating that you need to handle java.io.filenotfoundexception and java.io.ioexception. Recall that we can handle these using try/catch blocks. Place your file-related code in a try block and catch the exceptions, doing nothing for now when they are caught: // Write your code here catch (FileNotFoundException e) { catch (IOException e) { 5

6 Run your code now. Once it has completed, you should see two files appear in the left side of the IDE just below the src folder called customer1.txt and customer2.txt. If you open these files, you will notice that they each look weird like this: Amie FB BradM6 The files look weird because the information is stored as binary. As it turns out, when you open up binary information in a text editor (like notepad), the only information that will appear somewhat normal are Strings and chars since their byte values correspond to values that the text editor understands to be text. If we want to save many Customer objects to a file, we would need to duplicate the 5 or 6 lines of code that do the saving. It could be very wasteful. Instead of doing this in our test code, it is more efficient to make a Customer method to do this. Create the following method in the Customer class (you will need to import the two file-related classes from the java.io package): public void saveto(dataoutputstream afile) throws IOException { Copy the code that does the writing of the Customer's information into this method. Note that you won't use variables c1 and c2 now but you can replace it with the keyword this or even better you can access the 5 instance variables directly now instead of using the get methods. Make sure NOT to open nor close the file in this method, that is the responsibility of the method that called this one. Assume that the DataOutputStream has already been created and was passed in. As a result, the try block of our test code should now look like this make the appropriate changes: DataOutputStream out; out = new DataOutputStream(new FileOutputStream("customer1.txt")); c1.saveto(out); out.close(); out = new DataOutputStream(new FileOutputStream("customer2.txt")); c2.saveto(out); out.close(); catch (FileNotFoundException e) { catch (IOException e) { Re-run the CustomerTestProgram. It should still work. The code is shorter now and more efficient. How do we read the Customers back in again? Well, we can simply use a DataInputStream instead. This time, we'll make a static method so that we don't need to have a Customer already in order to load one from a file. Create the following static method in the Customer class: public static Customer readfrom(datainputstream afile) throws IOException { 6

7 Complete the method so that a Customer object is created and returned from the method. The code should make use of the DataInputStream's readutf(), readint(), readchar() and readfloat() methods to read and set the data for the customer. Test your code by adding the following to the end of the CustomerTestProgram and running it. You should see the correct values displayed that correspond to the original customer's data. DataInputStream in; in = new DataInputStream(new FileInputStream("customer1.txt")); System.out.println(c1.readFrom(in)); in.close(); in = new DataInputStream(new FileInputStream("customer2.txt")); System.out.println(c1.readFrom(in)); in.close(); catch (FileNotFoundException e) { catch (IOException e) { 6) Now we will save multiple customers to a common store.txt file. Write the following similar method in the Store class: public void saveto(dataoutputstream afile) throws IOException { Complete this method so that it loops through the Customer objects and saves each one of them to the file. Make sure that you call your saveto() method in the Customer class for each customer. Test your code by adding the following to the end of the StoreTestProgram file's main method: DataOutputStream out = new DataOutputStream(new FileOutputStream("store.txt")); walmart.saveto(out); out.close(); catch (FileNotFoundException e) { catch (IOException e) { Look at the resulting store.txt file. Did it work? Go to the Store class and write method below to read in the customers again. Notice that the code to actually read in the Customer object's data is missing. Write this code using the readfrom() method that you wrote in the Customer class. public static Store readfrom(datainputstream afile) throws IOException { Store s = new Store("?"); while (afile.available() > 0) { // Now read in a customer from the file and add him/her to the store return s; Test your code by adding the following to the end of the StoreTestProgram file's main method: DataInputStream in = new DataInputStream(new FileInputStream("store.txt")); walmart = Store.readFrom(in); in.close(); catch (FileNotFoundException e) { 7

8 catch (IOException e) { System.out.println("\n\nHere are the customers from the file's Store object:"); walmart.listcustomers(); Run the test code. If your code was written properly, you should see the customers with names beginning from A to Z listed twice the first list represents data from the original object and the second list represents data that was read in from the file. The two lists should be identical. 7) Now although we can save and load the Store as well as Customers, it would be nice to save everything as text so that we can browse through it with a text editor. Let's do this now. Go through all of your code in Store, Customer, and StoreTestProgram and do the following: Amie 14 F Brad 15 M 0.0 i. replace DataOutputStream and FileOutputStream with PrintWriter and FileWriter, respectively. ii. replace DataInputStream and FileInputStream with BufferedReader and FileReader, respectively. iii. replace all of the writexxx() code with println(). iv. replace all of the readxxx() code with readline(). You will need to convert the incoming age, gender and money strings into int, char and float types. Do you remember how to do this? We can say Integer.parseInt(aString) to an incoming string to convert it to an int. A similar approach can be used for floats. For chars, we simply do a charat(0) to get the first char of the incoming string. v. There is no method called available() for BufferedReader objects. Instead, there is a method called ready() which returns a boolean indicating whether or not the buffer is able to be read. So, replace afile.available() > 0 with afile.ready(). Run the StoreTestProgram it should work as before. However, open up the store.txt file to see what it looks like. It should look like this: Amie 14 F Brad 15 M 0.0 Cory 10 M Dave Modify your code so that a blank line separates the customers in the file as shown below. Make sure that your code still reads in the data properly: 8

9 Cory 10 M Dave 8) Now see if you can save the customers into the store.txt file (and read them back in again) with this file format: ,Amie,14,F, ,Brad,15,M, ,Cory,10,M, ,Dave,5,M,48.0 To read it in again, you will want to use the split() method from the String class. Recall an example of how to use it: String s1 = "Mark,Lanthier,48,M,false"; String[] tokens = s1.split(","); for(string token: tokens) System.out.println(token); The code above will produce the following output: Mark Lanthier 48 M false Test your code by re-writing the file using the StoreTestProgram, viewing the store.txt file to make sure that it saved in the correct format, and was able to be read in again. MORE CHALLENGING QUESTIONS: 9) Let's alter the code so that Ball objects also collide. Start by renaming the getplayers() method in the Game class to getmovableobjects() and making sure that it returns an ArrayList<MovableObject> of all objects that are instances of MovableObject. (i.e., just change "Player" everywhere to "MovableObject"). You will have to change the updateobjects() method accordingly to use this new method. Make sure that the Game class compiles before moving on. Run the code in the GameBoardTestProgram. You should notice that the ball stops in front of the wall to its right. However, there was no collision. The ball just happened to slow down and stop. So, no CollisionExceptions were generated for the ball. Try increasing the speed of the ball to 6 in the GameBoardTestProgram and then run the code again. You will notice that no exception was generated for the ball and that it went beyond the wall. What's up with that? Do you understand? Plot the ball's course and watch the speed (and location) as it slows down: 9

10 Notice how the ball "skipped over" the wall. Because the ball's speed causes it to move multiple grid locations at one, it can "skip over" certain locations in the grid, which may or may not contain walls. We did not notice this problem with the player because it was moving at speed 1, but if the player was to move faster, it would have the same problem. How can we check for collisions at this speed? Do you have any ideas? To check for collisions, we could check ALL the locations in between the last location and the current desired location to make sure that there were no walls along the way. Change the updateobjects() method in the Game class to check all of the locations between the MovableObject's last location and current location. Keep your code simply by assuming that MovableObjects always move either up, down, left or right never at any other angle. Re-compile your code and make sure that the ball collides properly. You should see exactly 2 collisions one for the Player and one for the Ball: #################### # $ # # # # # ########### # # ##### $ # # ^ # # # # # # # # # # # o# # $ # # # #################### Adjust the code so that when a Ball collides, it changes direction (i.e., bounces away). It's tricky. Start perhaps by simply negating the speed. Test your code. Try changing the ball's speed to 8 and then to 2. For speed of 2, go to the ball's moveforward() method and adjust it so that the ball does not slow down. 10) Let us save and then load the Store as an object (as opposed to binary and text as we have done). Recall that to save as whole objects, we simply need to implement the Serializable interface. Add implements java.io.serializable to your class definitions of Customer and Store. Add the following to the bottom of your StoreTestProgram so that it saves the Store using an ObjectOutputStream using the following lines: ObjectOutputStream objout; objout = new ObjectOutputStream(new FileOutputStream("store2.txt")); objout.writeobject(walmart); objout.close(); 10

11 catch(ioexception e) { You DO NOT need to add any methods in the Customer or Store classes! Just re-run the test program. Look at the store2.txt file produced. It looks a little weird. In fact, it is a binary format which contains information about the class. Add the following to the bottom of your StoreTestProgram so that it reads in the Store using an ObjectInputStream using the following lines: walmart = new Store("Walmart"); ObjectInputStream objin; objin = new ObjectInputStream(new FileInputStream("store2.txt")); walmart = (Store)objIn.readObject(); objin.close(); catch(ioexception e) { System.out.println("Here are the customers from the file's Store object:\n"); walmart.listcustomers(); The compiler will complain that you need to also now catch a ClassNotFoundException. That is because JAVA will try to reconstruct the Store objects itself upon reading it from the file and there may be problems creating objects if the file is corrupt, for example. You will need to add another catch block to catch this error. Now recompile and run the code. Ok so it does not seem very impressive does it? Let's look at how powerful this object saving/loading actually is. Go to your Customer and Store classes and comment out the saveto() and readfrom() methods. Also, comment out the try/catch blocks in your CustomerTestProgram and StoreTestProgram that were from our PrintWriter and BufferedReader testing. Run the code. Your code will STILL work!! That is because these methods are no longer used, of course. So, when writing whole objects to a file, you do not need to do anything more that simply implement the Serializable interface. The readobject() and writeobject() methods are available for free! Now do you see the benefits? Everything is not as "peachy" as it sounds though. Go to the Customer class and change the money variable to a double instead of float. Change the getmoney() method to return a double instead of float. Now go to the StoreTestProgram and comment out the first try/catch block that saves the object to a file. There should only be one try block remaining in the test code. Run the code. It should run ok, but in fact, there was a problem. In the catch block for the IOException, add this line, then re-compile and run again : System.out.println(e.getMessage()); In the output you should notice that the following error is displayed: Customer; local class incompatible: stream classdesc serialversionuid = , local class serialversionuid = The Store object is unable to be read in now!! As it turns out, the way the Customer and Store objects are stored in the file is dependent on the class definition itself. Since we changed the Customer class definition, we can no longer read in the store.txt file which is based on the previous version of the Customer class. JAVA "stamps" each class with an ID called a serialversionuid. This changes each time the class is modified in some way such as modifying or deleting instance variables and other methods etc 11

12 Now uncomment the 2nd last try/catch block in the StoreTestProgram so that the store2.txt file is rewritten to the file using the new Customer class definition. The program should now be able to read it back in again without problems. Try it. Do you see the disadvantage of using ObjectStreams? Once you save the data, you need to keep the classes unchanged if you want to be able to read it back in. Of course, it is easiest to keep a copy of the code that was able to read the object back in. Later you can write programs that read it in and convert it to the new format. But it can really be a hassle. So, be aware of these issues when saving as objects. 11) Get your code from Tutorial 9 which represented the DVDCollection GUI that allowed you to sort the DVD objects. Add Save and Load menu options to the File menu. Complete the code so that various DVDCollections can be saved and loaded from a file using either a binary or text-based format. Use the FileChooser dialog box (see chapter 7 of the notes) to allow the user to pick the file name to save and load. Test your code to make sure that it works. REMINDERS: Don't forget to save all of your work on a USB drive, or it to yourself. Make sure to complete the tutorial at home, as it will give you extra practice. 12

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved. Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,

More information

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003 Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data

More information

1.00 Lecture 30. Sending information to a Java program

1.00 Lecture 30. Sending information to a Java program 1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes

More information

Performing input and output operations using a Byte Stream

Performing input and output operations using a Byte Stream Performing input and output operations using a Byte Stream public interface DataInput The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of

More information

Streams and File I/O

Streams and File I/O Chapter 9 Streams and File I/O Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch

More information

COMP1406 Tutorial 3. // A simple constructor public Customer(String n, int a, char g, float m) { name = n; age = a; gender = g; money = m; }

COMP1406 Tutorial 3. // A simple constructor public Customer(String n, int a, char g, float m) { name = n; age = a; gender = g; money = m; } COMP1406 Tutorial 3 Objectives: Learn how to create multiple objects that interact together. To get practice using arrays of objects. Understand the private and public access modifiers. Getting Started:

More information

Chapter 12. File Input and Output. CS180-Recitation

Chapter 12. File Input and Output. CS180-Recitation Chapter 12 File Input and Output CS180-Recitation Reminders Exam2 Wed Nov 5th. 6:30 pm. Project6 Wed Nov 5th. 10:00 pm. Multitasking: The concurrent operation by one central processing unit of two or more

More information

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO) I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:

More information

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Files Two types: Text file and Binary file Text file (ASCII file) The file data contains only ASCII values

More information

Data Structures. 03 Streams & File I/O

Data Structures. 03 Streams & File I/O David Drohan Data Structures 03 Streams & File I/O JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

Job Migration. Job Migration

Job Migration. Job Migration Job Migration The Job Migration subsystem must provide a mechanism for executable programs and data to be serialized and sent through the network to a remote node. At the remote node, the executable programs

More information

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading. Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Assn 3 posted. Announcements Final on June 14 or 15?

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

Chapter 11: Exceptions and Advanced File I/O

Chapter 11: Exceptions and Advanced File I/O Chapter 11: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 11 discusses the following main topics:

More information

Lecture 7. File Processing

Lecture 7. File Processing Lecture 7 File Processing 1 Data (i.e., numbers and strings) stored in variables, arrays, and objects are temporary. They are lost when the program terminates. To permanently store the data created in

More information

Active Learning: Streams

Active Learning: Streams Lecture 29 Active Learning: Streams The Logger Application 2 1 Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text

More information

Chapter 12: Exceptions and Advanced File I/O

Chapter 12: Exceptions and Advanced File I/O Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All

More information

Chapter 10. IO Streams

Chapter 10. IO Streams Chapter 10 IO Streams Java I/O The Basics Java I/O is based around the concept of a stream Ordered sequence of information (bytes) coming from a source, or going to a sink Simplest stream reads/writes

More information

1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams

1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams 1.00 Lecture 31 Streams 2 Reading for next time: Big Java 18.6-18.8, 20.1-20.4 The 3 Flavors of Streams In Java, you can read and write data to a file: as text using FileReader and FileWriter as binary

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

CN208 Introduction to Computer Programming

CN208 Introduction to Computer Programming CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every

More information

What is Serialization?

What is Serialization? Serialization 1 Topics What is Serialization? What is preserved when an object is serialized? Transient keyword Process of serialization Process of deserialization Version control Changing the default

More information

COMP1406 Tutorial 5. Objectives: Getting Started: Tutorial Problems:

COMP1406 Tutorial 5. Objectives: Getting Started: Tutorial Problems: COMP1406 Tutorial 5 Objectives: Learn how to create a window with various components on it. Learn how to create a Pane and use it in more than one GUI. To become familiar with the use of Buttons, TextFields

More information

CS 251 Intermediate Programming Java I/O Streams

CS 251 Intermediate Programming Java I/O Streams CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package

More information

File IO. Binary Files. Reading and Writing Binary Files. Writing Objects to files. Reading Objects from files. Unit 20 1

File IO. Binary Files. Reading and Writing Binary Files. Writing Objects to files. Reading Objects from files. Unit 20 1 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files Unit 20 1 Binary Files Files that are designed to be read by programs and that consist of a sequence

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Special error return Constructors do not have a return value What if method uses the full range of the return type? 23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

Simple Java Input/Output

Simple Java Input/Output Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it

More information

HST 952. Computing for Biomedical Scientists Lecture 8

HST 952. Computing for Biomedical Scientists Lecture 8 Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java

More information

14.3 Handling files as binary files

14.3 Handling files as binary files 14.3 Handling files as binary files 469 14.3 Handling files as binary files Although all files on a computer s hard disk contain only bits, binary digits, we say that some files are text files while others

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies Streams A stream is a sequence of data. In Java a stream is composed of bytes. In java, 3 streams are created for us automatically. 1. System.out : standard output stream 2. System.in : standard input

More information

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams In this lab you will write a set of simple Java interfaces and classes that use inheritance and polymorphism. You will also write code that uses

More information

Exceptions and Working with Files

Exceptions and Working with Files Exceptions and Working with Files Creating your own Exceptions. You have a Party class that creates parties. It contains two fields, the name of the host and the number of guests. But you don t want to

More information

I/O Streams. Object-oriented programming

I/O Streams. Object-oriented programming I/O Streams Object-oriented programming Outline Concepts of Data Streams Streams and Files File class Text file Binary file (primitive data, object) Readings: GT, Ch. 12 I/O Streams 2 Data streams Ultimately,

More information

Files and Streams

Files and Streams Files and Streams 4-18-2006 1 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any questions about the assignment? What are files and why are

More information

Events and Exceptions

Events and Exceptions Events and Exceptions Analysis and Design of Embedded Systems and OO* Object-oriented programming Jan Bendtsen Automation and Control Lecture Outline Exceptions Throwing and catching Exceptions creating

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 5. Exceptions. I/O in Java Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Exceptions Exceptions in Java are objects. All

More information

Streams and File I/O

Streams and File I/O Walter Savitch Frank M. Carrano Streams and File I/O Chapter 10 Objectives Describe the concept of an I/O stream Explain the difference between text and binary files Save data, including objects, in a

More information

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Chapter 17 Binary I/O 1 Motivations Data stored in a text file is represented in human-readable form. Data stored in a binary file is represented in binary form. You cannot read binary files. They are

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Data stored in variables and arrays is temporary It s lost when a local variable goes out of scope or when

More information

Java Programming Unit 7. Error Handling. Excep8ons.

Java Programming Unit 7. Error Handling. Excep8ons. Java Programming Unit 7 Error Handling. Excep8ons. Run8me errors An excep8on is an run- 8me error that may stop the execu8on of your program. For example: - someone deleted a file that a program usually

More information

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

More information

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

Many Stream Classes. File I/O - Chapter 10. Writing Text Files. Text Files vs Binary Files. Reading Text Files. EOF with hasmoreelements()

Many Stream Classes. File I/O - Chapter 10. Writing Text Files. Text Files vs Binary Files. Reading Text Files. EOF with hasmoreelements() File I/O - Chapter 10 Many Stream Classes A Java is a sequence of bytes. An InputStream can read from a file the console (System.in) a network socket an array of bytes in memory a StringBuffer a pipe,

More information

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes.  Debugging tools Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Example: Copying the contents of a file

Example: Copying the contents of a file Administrivia Assignment #4 is due imminently Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in the front office for a demo time Dining Philosophers code is online www.cs.ubc.ca/~norm/211/2009w2/index.html

More information

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת A Typical Program Most applications need to process some input and produce some output based on that input The Java IO package (java.io) is to make that possible

More information

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012 CMPSCI 187: Programming With Data Structures Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012 Files and a Case Study Volatile and Non-Volatile Storage Storing and Retrieving Objects

More information

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)

More information

CS193j, Stanford Handout #26. Files and Streams

CS193j, Stanford Handout #26. Files and Streams CS193j, Stanford Handout #26 Summer, 2003 Manu Kumar Files and Streams File The File class represents a file or directory in the file system. It provides platform independent ways to test file attributes,

More information

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Software 1 with Java. Recitation No. 7 (Java IO) May 29, Software 1 with Java Recitation No. 7 (Java IO) May 29, 2007 1 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating files Classes

More information

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015 COMP-202: Foundations of Programming Lecture 22: File I/O Jackie Cheung, Winter 2015 Announcements Assignment 5 due Tue Mar 31 at 11:59pm Quiz 6 due Tue Apr 7 at 11:59pm 2 Review 1. What is a graph? How

More information

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output. CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics

More information

COMP1406 Tutorial 1. Objectives: Getting Started:

COMP1406 Tutorial 1. Objectives: Getting Started: COMP1406 Tutorial 1 Objectives: Write, compile and run simple Java programs using the IntelliJ Idea IDE. Practice writing programs that require user input and formatted output. Practice using and creating

More information

CS193j, Stanford Handout #25. Exceptions

CS193j, Stanford Handout #25. Exceptions CS193j, Stanford Handout #25 Summer, 2003 Manu Kumar Exceptions Great Exceptations Here we'll cover the basic features and uses of exceptions. Pre-Exceptions A program has to encode two ideas -- how to

More information

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2 Java IO - part 2 BIU OOP Table of contents 1 Basic Java IO What do we know so far? What s next? 2 Example Overview General structure 3 Stream Decorators Serialization What do we know so far? What s next?

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

Java Programming Lecture 9

Java Programming Lecture 9 Java Programming Lecture 9 Alice E. Fischer February 16, 2012 Alice E. Fischer () Java Programming - L9... 1/14 February 16, 2012 1 / 14 Outline 1 Object Files Using an Object File Alice E. Fischer ()

More information

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CISC 323 (Week 9) Design of a Weather Program & Java File I/O CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming

More information

Lesson 3: Accepting User Input and Using Different Methods for Output

Lesson 3: Accepting User Input and Using Different Methods for Output Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program

More information

CS 2113 Software Engineering

CS 2113 Software Engineering CS 2113 Software Engineering Java 6: File and Network IO https://github.com/cs2113f18/template-j-6-io.git Professor Tim Wood - The George Washington University Project 2 Zombies Basic GUI interactions

More information

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p() 23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method

More information

Software 1. Java I/O

Software 1. Java I/O Software 1 Java I/O 1 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating files Classes for serializing objects 2 Streams A stream

More information

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

Exceptions Binary files Sequential/Random access Serializing objects

Exceptions Binary files Sequential/Random access Serializing objects Advanced I/O Exceptions Binary files Sequential/Random access Serializing objects Exceptions No matter how good of a programmer you are, you can t control everything. Other users Available memory File

More information

CS 180 Final Exam Review 12/(11, 12)/08

CS 180 Final Exam Review 12/(11, 12)/08 CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics

More information

CS112 Lecture: Streams

CS112 Lecture: Streams CS112 Lecture: Streams Objectives: Last Revised March 30, 2006 1. To introduce the abstract notion of a stream 2. To introduce the java File, Input/OutputStream, and Reader/Writer abstractions 3. To show

More information

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits) The Java I/O System Binary I/O streams (ASCII, 8 bits) InputStream OutputStream The decorator design pattern Character I/O streams (Unicode, 16 bits) Reader Writer Comparing binary I/O to character I/O

More information

I/O STREAM (REQUIRED IN THE FINAL)

I/O STREAM (REQUIRED IN THE FINAL) I/O STREAM (REQUIRED IN THE FINAL) STREAM A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents

More information

Previous to Chapter 7 Files

Previous to Chapter 7 Files Previous to Chapter 7 Files Recall Scanner from Part I notes. A scanner object can reference a text file Scanner f = new Scanner(new File("file name goes here")); Scanner methods can be applied to reading

More information

Dining philosophers (cont)

Dining philosophers (cont) Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs this week for a demo time Office hour today will be cut short (11:30) Another faculty

More information

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output Overview 7 Streams and files import java.io.*; Binary data vs textual data Simple file processing - examples The stream model Bytes and characters Buffering Byte streams Character streams Binary streams

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

Stream Manipulation. Lecture 11

Stream Manipulation. Lecture 11 Stream Manipulation Lecture 11 Streams and I/O basic classes for file IO FileInputStream, for reading from a file FileOutputStream, for writing to a file Example: Open a file "myfile.txt" for reading FileInputStream

More information

CSPP : Introduction to Object-Oriented Programming

CSPP : Introduction to Object-Oriented Programming CSPP 511-01: Introduction to Object-Oriented Programming Harri Hakula Ryerson 256, tel. 773-702-8584 hhakula@cs.uchicago.edu August 7, 2000 CSPP 511-01: Lecture 15, August 7, 2000 1 Exceptions Files: Text

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 05/07/2012 10:31 AM Input / Output Streams 2 of 21 05/07/2012 10:31 AM Java I/O streams

More information

Files and IO, Streams. JAVA Standard Edition

Files and IO, Streams. JAVA Standard Edition Files and IO, Streams JAVA Standard Edition Java - Files and I/O The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent

More information

Abstract Classes, Exceptions

Abstract Classes, Exceptions CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();

More information

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax Tirgul 1 Today s topics: Course s details and guidelines. Java reminders and additions: Packages Inner classes Command Line rguments Primitive and Reference Data Types Guidelines and overview of exercise

More information

FILE I/O IN JAVA. Prof. Chris Jermaine

FILE I/O IN JAVA. Prof. Chris Jermaine FILE I/O IN JAVA Prof. Chris Jermaine cmj4@cs.rice.edu 1 Our Simple Java Programs So Far Aside from screen I/O......when they are done, they are gone They have no lasting effect on the world When the program

More information

Chapter 6 Classes and Objects

Chapter 6 Classes and Objects Chapter 6 Classes and Objects Hello! Today we will focus on creating classes and objects. Now that our practice problems will tend to generate multiple files, I strongly suggest you create a folder for

More information

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as

More information

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I Hashing Reading: L&C 17.1, 17.3 Eck 10.3 Defne hashing Objectives Discuss the problem of collisions in hash tables Examine Java's HashMap implementation of hashing Look at HashMap example Save serializable

More information

Simple Java I/O. Part I General Principles

Simple Java I/O. Part I General Principles Simple Java I/O Part I General Principles Streams All modern I/O is stream based A stream is a connec8on to a source of data or to a des8na8on for data (some8mes both) An input stream may be associated

More information

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide Module 10 I/O Fundamentals Objectives Upon completion of this module, you should be able to: Write a program that uses command-line arguments and system properties Examine the Properties class Construct

More information

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition

More information