New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Object Oriented Programming

by: Luisa Beer

Object Oriented Programming COP 3330

Luisa Beer
University of Central Florida
GPA 3.78


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Computer Programming

This 37 page Class Notes was uploaded by Luisa Beer on Thursday October 22, 2015. The Class Notes belongs to COP 3330 at University of Central Florida taught by Staff in Fall. Since its upload, it has received 41 views. For similar materials see /class/227471/cop-3330-university-of-central-florida in Computer Programming at University of Central Florida.

Similar to COP 3330 at University of Central Florida

Popular in Computer Programming


Reviews for Object Oriented Programming


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/22/15
Aggregation The HASA Relationship Thus far most of our examples have involved quotsimplequot classes in that the instance variables of the classes have all been primitives However this is not a requirement In fact we have already seen examples where one of the instance variables of a class we defined was a String which is not a primitive Complex programs however require complex classes where the individual components of the class may be other objects Conceptually we can come up with real life examples A Car object HASA Wheel object In fact it would have four Note that this relationship is a different one than the relationship between a Sports Car and a Car Namely A Car is NOT a Wheel but a Sports Car ISA Car Another analogy that should make the difference clear is as follows A person HASA arm but a person IS NOT an arm A football player ISA person but does not HAVE a person We will focus on two examples for this lecture 1 A Contact object will store information for one person An AddressBook object will store many Contact objects and will maintain this list 2 We will build a Lemonade class that allows us to play the game Lemonade The Lemonade object will comprise the following components a a BankAccount object to keep the money for the game b the number of bags of sugar owned c the number of bags of lemons owned d the price of a single cup of lemonade e the name of the Lemonade stand owner In this latter example the BankAccount object is comprised of the following components a the name of the owner b the amount of money in savings c the amount of money in checking d the interest rate for the savings account In addition in order to run a game of Lemonade we39ll need to use a Weather object Polymorphism The basic idea behind polymorphism is that the decision of which method is called can sometimes be delayed till runtime To make a reallife analogy consider the following Imagine that you invited a guest speaker from NASA Imagine that everyone who works at NASA is of type NASAEmployee In code imagine that you instantiated a variable of type NASAEmployee named UnknownSpeaker Then you would have her speak UnknownSpeakerspeak Now you could relay this command before knowing WHO was speaking But at runtime depending on who the speaker is they may talk about different things If you get an astronaut like Sally Ride she might talk about what it39s like to experience zero gravity for several days straight If on the other hand you got a project manager she might talk about how to create a time line Since you don39t know beforehand that you are going to get a speaker it would be illegal to do the following UnknownSpeakerzerogravitydemo since only an Astronaut can do the zero gravity demo and when you make the initial invitation you DON39T know that you39re going to get an Astronaut But since all NASA Employees can speak it39s perfectly valid when you extend the invitation to ask them to do so and then when the actual speech happens it is tailored by the specific NASA Employee that comes to speak Motivation behind polymorphism An example of a situation where polymorphism would be desirable is processing payroll Each employee must get paid but different employees get paid differently An inheritance structure more easily encapsulates the differences between how everyone gets paid in a seamless manner than other systems For example you could take care of paying everyone as follows Employee workers new Employee100 Stuff happens here Here we pay everyone for Employee worker workers workerpay The neat thing here is that even though each array element is a reference to an Employee the actual object to which is being referred could easily be a specialized Employee such as a SalariedEmployee Even though we might not know that workers3 is a SalariedEmployee before runtime when the program runs it can pay the SalariedEmployee in the appropriate manner because the pay would be overridden in the SalariedEmployee class In general it allows you to have a collection of general Objects and perform some action on all of them but that action can be modified if some of the general Objects are of a more speci c type Example Coordinate amp ColorCoordinate toString The Coordinate class manages an ordered pair of an integer and a character For simplicity39s sake and to focus on polymorphism the class only has constructors accessors a toString method and a couple equals methods We will examine to possible scenarios for the toString method 1 It is ONLY defined in Coordinate 2 It is defined in both Coordinate and ColorCoordinate In the former situation no matter whether the reference is a Coordinate reference or a ColorCoordinate reference the toString in Coordinate will be called This situation is generally straightforward There isn39t a choice between multiple toString implementations to really consider It39s clear that the toString in Object won39t get called In the latter situation the type of the actual Object matters If a Coordinate reference c is referring to a ColorCoordinate object then ctoString will invoke the toString method in the ColorCoordinate class In general the rule is that syntactically the method call must be valid within the class of the REFERENCE So since c is a Coordinate reference we MUST have a toString method defined for a Coordinateobject But once this is satis ed then we find that at runtime if we notice that c is referring to an Object of the inheritedsubclass class and that inheritedsubclass class overrides that particular method then that is the one that gets called at run time Example Coordinate amp ColorCoordinate equals We could potentially define four separate equals methods total 1 public boolean equalsCoordinate c in Coordinate 2 public boolean equalsColorCoodinate c in Coordinate 3 public boolean equalsCoordinate c in ColorCoordinate 4 public boolean equalsColorCoodinate c in ColorCoor In the chart below each column refers to one of the four methods above and each row represents a possible scenario of which methods are de ne Here are some of the situations we39ll consider Situation Method 1 Method 2 Method 3 Method 4 1 Yes No No No 2 Yes Yes No No 3 Yes No Yes No 4 Yes No No Yes 5 Yes Yes Yes No 6 Yes Yes Yes Yes One key idea to remember is the following type matching to determine which method gets called for PARAMETERS is NOT dynamic The compiler identifies the type of the parameter and that is what is used to determine what method gets called In our situations above it39s clear what happens in situation 1 But after that it gets a bit more confusing so let39s try to lay down some rules to help use deal with the cases above without having to remember 6 separate sets of rules General Rules for Polymorphism To help explain the rules below examples will be given In each of the examples assume that A inherits from Object B inherits from A C inherits from B and D from C 1 First you must find a method that matches the signature of the method called in the class of the reference of the object upon which the method was called This if the call to a method is of the form omethodcallparameters here then there must be a method call in the class of the reference 0 OR a class that the class of the reference from o inherits from that fits the method signature If there is not then the code should produce a syntax error Note In finding a method call that matches remember that the types of the actual parameters are based on the types of the references and not based on the types of the objects they are referring to So for example if the reference of o is of type B and o is referencing an object of type C then a method of the signature of the method call must be found in either the Object class the class A or the class B If it is ONLY in class C then this would result in a syntax error 2 Once we find a method call that matches in the class of the reference of 0 then we check the type of object to which 0 is referring To finalize the method actually called we start in the class of the object and work our way down the hierarchy until we find a method that matches the appropriate signature Basically once a method call is accepted as being syntactically valid then we start over in determining which method call actually runs at runtime So for example if the reference of o is of type B and o is referencing an object of type D then we would FIRST look in class D to see if there was a method matching the signature of the method call In checking for this match we use the types of the references of the actual parameters If there is that is the method that gets called If not we then look to class C If there is a method in class C that matches then that is the method that gets called If not then we are guaranteed a match for a method in class B and this is the one that gets called Applying our Rules Let39s apply our rules to situation 6 for the equals method in the Coordinate and ColorCoordinate classes Here are the four objects initially created Coordinate test new ColorCoordinate339a39quotGreenquot ColorCoordinate red new ColorCoordinate339a39quotRedquot ColorCoordinate blue new ColorCoordinate339a39quotBluequot Coordinate nocolor new Coordinate339a39 Now let39s consider determining WHICH of the four methods gets called for each of the following calls nocoloreguals red red is a ColorCoordinate reference and since nocolor is referring to a Coordinate the method that gets called is Method 2 redeguals nocolor nocolor is a Coordinate reference and since red is referring to a ColorCoordinate the method that gets called is Method 3 redeguals bluez Method 4 gets called since both references are of type ColorCoordinate testeguals bluez blue is a ColorCoordinate reference so initially we match with Method 2 but using polymorphism we see the test actually refers to a ColorCoordinate object so Method 4 is executed blueegualsgtest Here method 3 gets executed because test is a Coordinate reference and this doesn39t dynamically get binded However if a method is called upon test in equals polymorphism could occur for THAT call A couple exercises 1 Imagine adding a ThreeDCC that extended ColorCoordinate and adding two equals methods to it one that takes in a Coordinate and another that takes in a ThreeDCC You can actually add this fairly easily In this situation identify the equals methods that get called in the following sequence of code Coordinate test new ColorCoordinate339a39quotGreenquot ColorCoordinate red new ThreeDCC339a3910quotRedquot ThreeDCC blue new ThreeDCC339a3979quotBluequot Coordinate nocolor new Coordinate339a39 testequalsred redequalstest blueequalsred redequalsblue nocolorequalsred nocolorequalstest blueequalstest 2 Actually write a small ThreeDCC class and test out your answers You don39t need to write a meaningful equals method just enough to test the method calls above Inheritance IS A Relationship We39ve talked about the basic idea of inheritance before but we haven39t yet seen how to implement it Inheritance encapsulates the IS A Relationship A String IS A Object A Corvette IS A Card A ThreeDimensionalPoint IS A Point A Clarinet IS A Musicallnstrument In this lecture we39ll look at two examples of inheritance 1 A Coordinate and ColorCoordinate class 2 An extension of the Fraction class the MixedFraction class When defining an inherited class we must explicitly state that we are extending another class as follows public class ColorCoordinate extends Coordinate In this situation we refer to Coordinate as the base class We can also refer to it as the superclass ColorCoordinate is known as the derived class or subclass Beyond that there are quite a few rules that we must discuss First there are some changes that we must make to our original class if we had not created it with the intention of inheriting from it Let39s take a look at the Coordinate class to see these changes Protected Visibility Modi er In a typical class we make our instance variables private However if we did this and we created a derived class that inherited from our original class then we would NOT have access to the instance variables of the base class in our derived class This could prove to be problematic if we want access to these instance variables In some instances we won39t need it because the methods in the base class can adequately manipulate these variables Instead if we declare our instance variables to be protected then we have access to them BOTH in the current class AND all inherited classes Here is the beginning of the Coordinate class public class Coordinate protected int num protected char c The rest of the Coordinate class looks like other examples of simple classes we39ve seen The goal of this class is to manage a Coordinate object that is indexed by a number and a letter much like a location in the game of Battleship Constructors in a subclass We might think that a ColorCoordinate constructor might look like this public ColorCoordinateint num char c String color thisnum num thisc c thiscolor color But if you really think about it this is redundant The reason this is redundant is that we ALREADY have a constructor in the Coordinate class that takes care of initializing both num and c The whole point of inheritance is to UTILIZE the code from the base class Thus we have an explicit way of calling the constructor from a super class so that we can REUSE this code So our constructor will ACTUALLY look like this public ColorCoordinateint num char c String color supernum c thiscolor color The super call without any object before it automatically makes a call to the appropriate constructor from the direct base class of ColorCoordinate which is Coordinate This call will properly assign num and c When it finishes all we have to do is assign color Default Constructors in a subclass If we make NO reference to super in a constructor of our subclass then a call to the DEFAULT constructor of the base class is made anyway Thus when we see the following code in the ColorCoordinate class public ColorCoordinateString color thiscolor color What is REALLY executed by the computer is the following public ColorCoordinateString color SHDCFO thiscolor color So our whole object gets initialized with Random instance variables as is specified in the default constructor in the Coordinate class In summary in all super class constructors we do NOT need to initialize ALL instance variables explicitly Instead we can reuse code from the base class constructors in two ways 1 Explicitly calling super which will invoke the constructor of your choice 2 Omitting the call to super which will invoke the default constructor of the base class anyway Other Instance Methods in a Subclass When we design methods for a subclass remember that we MUST look at the functionality already provided to us from the base class In particular there39s no need to reinvent the wheel We already have access to all of these methods so there39s NO need to rede ne any of these methods if we want to use them exactly as they are Here are the types of design decisions we are free to make 1 Keep methods from the base class and don39t write a similar method in the subclass 2 Rede ne a method in the subclass because you want it working differently for an object of the subclass than an object of the base class 3 Define a new method that is specific to the subclass that isn39t defined in the base class at all In our example we have examples of all three choices 1 getNum and getC exist in Coordinate only because they are ALSO adequate for a ColorCoordinate object 2 The toString method is rede ned for ColorCoordinates because it works a bit differently for ColorCoordinates than it works for Coordinates 3 The getColor method only makes sense for the ColorCoordinate class It makes no sense for the Coordinate class so it39s not included in that class at all Redefining Methods in a Subclass To rede ne methods in a subclass you use the same method signature as the base class but place the method in the subclass From here you are free to define the method as you see fit Even though you are redefining the method you may nd it useful to CALL the method of the base class of the same name To do this you must invoke the call using the super keyword Unlike constructors Where super is automatically invoked in other methods it is NOT You have to EXPLICITLY call super public String toString return supertoString quot Color quot color Technically speaking the reason the equals method is NOT redefined in the ColorCoordinate class is because its method signature public boolean equalsColorCoordinate sample IS different than the equals method in the Coordinate class public boolean equalsCoordinate sample Furthermore note that you are not REQUIRED to make a call to super in a method in a subclass that is redefining a preexisting method in a base class Defining New Methods in a Subclass If you want MORE functionality in your subclass you have the right to define new methods in it that DON39T already exist at all in the base class For example for the Primate class you might NOT define a method readNewspapel O but you WOULD de ne it for the Human class that inherits from Primate In our example there are two newly defined methods public boolean equalsColorCoordinate sample which was just discussed This is newly defined because it takes in a ColorCoordinate object something that is NOT done in the Coordinate class method The other example is the following public String getColor return color This simply doesn39t make sense for a regular Coordinate object Using an Object of a Subclass Luckily this part is easy You use an object of a subclass exactly as you use any object You declare a reference and then create an object by calling the constructor Then you can call methods on that object as desired What is tricky is polymorphism which is what we39ll look at in a future lecture In particular this deals with what method gets called when there are multiple methods whose signatures match the called method Secondly it39s important to focus on two details when determining what method gets called when there39s ambiguity 1 The type of each reference involved 2 The type of each corresponding object involved Reading from Input Files in Java This can be done extremely similarly to reading from the keyboard A Scanner object can still be used But instead of passing Systemin into the constructor a File object must be passed in Scanner n new Scannernew Filequotanyfiletxtquot In order to create a File object the File constructor must be called This constructor simply takes in a String that stores the name of the file Thus in a single statement we can set a Scanner object to read from a file instead of the keyboard Once the Scanner object is quotset upquot then you use it EXACTLY as we have been using Scanner objects until now Use the following methods next nextInt and nextDouble There are other methods but these are the ones you39ll be using most frequently The only difference between reading from the keyboard and a file is that you should close a file once you are done reading from it Thus you must close the appropriate Scanner object The name of the method is close and it takes no parameters finclose Arrays in Java Just like all other nonprimitives in Java arrays are references Unlike C all arrays are dynamically allocated This means that the size of an array is always specified at runtime Since a dynamic allocation is done we use the new keyword as follows int values new int10 This allocates an array of size 10 that values references Consider the following picture From this point we use arrays of primitives exactly as they would be used in C To reference an individual array slot we use the operator The following segment of code initializes each slot in the array values to 0 for int i0 iltvalueslength i valuesi 0 One key idea to notice here that is different than C is that you can access the length of an array using the length field Note that length is a public variable for all arrays Thus there are no parentheses which would indicate a method call Let39s look at an example that utilizes Java39s dynamic array allocation capabilities Arrays of Objects It39s important to note that when an array of references is allocated NO actual objects are allocated For example the following statement doesn39t actually create ANY GiftCard objects GiftCard wallet new GiftCard10 Instead the picture looks like this Now in order for this array to actually store GiftCard objects we must create them individually Here39s a segment of code that could do it for int i0 iltwalletlength i SystemoutprintlnquotEnter your rst and last namequot String first stdinnext String last stdinnext SystemoutprintlnquotEnter the amount of this cardquot double money stdinnext Walleti new GiftCardfirst last money Now the picture looks like this Vector Class Java provides a few classes that allow us to manage collections of objects Today we39ll discuss the Vector class which stores a group of objects One of the quotlimitationsquot of an array in C is that it can only store one type of object In Java a Vector can store different types of objects Actually so can an array Secondly arrays in C are of a fixed size Actually you can also declare dynamically allocated arrays in C The Vector class in Java essentially handles both of these issues very well A Vector object can arbitrarily grow and shrink as needed without the user worrying about any of the details Furthermore a Vector can store different types of objects Well this is a bit of a stretch actually The manner in which Java gets away with having Vectors that can store different types of objects is through its quottreequot of inheritance All non primitives are objects and some objects inherit from others For example if I wrote a Car class I could write a SportsCar class that inherited all the methods and variables of the Car class but then maybe had some extra variables and methods that were speci c to the SportsCar Furthermore then I could maybe have a Corvette class that inherited from SportsCar It would retain all the attributes of the SportsCar class but then have some of its extra attributes In this example we have the following SportsCar inherits from Car so a SportsCar object ISA Car object Corvette inherits from SportsCar so a Corvette object ISA SportsCar object AND a Car object Java also provides a very basic class called Object Every non primitive class automatically inherits from Object Thus in a way all nonprimitives are valid quotObjectquot objects Thus if we create an array of Object or a Vector of Object then that collection can store ANY sort of nonprimitive ranging from a Time object to a String object to a Corvette object In the old version of Java the way to create an empty Vector was as follows Vector v new Vector This looks like a regular default constructor In the new version of Java templates are used This essentially means that some classes can be based upon a quottemplatequot class where you fill in the class you desire For a Vector object you are allowed to declare a Vector of any type of class Here is how we can declare a Vector of class Object VectorltObjectgt v new VectorltObjectgt Thus added to the name of the class is ltTgt where T is replaced with the type of object you want the vector to store If you wanted to create a Vector of String objects you39d do the following VectorltStringgt v new VectorltStringgt Some Methods in the Vector Class Appends this vector with a new element with value v void addElementT v Inserts value v into this Vector such that v has index i Any preexisting elements with indices i or greater are shifted backwards by one position void insertElementAtT v int i If i is a valid index in this Vector then the ith element is set to v Otherwise an ArrayIndexOutOfBoundsException is thrown void setElementAtT v int i Returns the number of elements in this Vector int size If i is a valid index in this Vector it returns the ith element otherwise an ArrayIndexOutOfBoundsException is thrown T elementAtint i Returns whether this Vector has an element with value v boolean contains0bject v In essence a Vector is similar to an array except that there is an extra level of data abstraction going on Rather than directly accessing the array the user indirectly interacts with the array through the public methods provided in the Vector class Some Details about Using a Vector Most of the methods are quite selfexplanatory but a couple things need to be mentioned 1 When values are extracted from a Vector of Objects how can we make them the correct type 2 Can we insert elements in arbitrary indices or do the elements always have to occupy the first set of indices starting at 0 In order to properly use an Object extracted from a Vector you must cast it to the appropriate class like so String middle StringvelementAt1 In this example the extracted item is an Object but is also known to be a String Casting it to a string allows us to have a String reference middle reference it Note that the cast is NOT necessary when adding Strings into the Vector The answer to the second question is no You are not allowed to insert an element into index 20 if indices 0 through 19 aren39t already filled Invoking Class Methods Static Sometimes methods inside of a class are NOT speci c to an object of the class but simply pertain to the class itself In order to call these methods you do NOT need to call them on an object of the class Rather you may call them simply my specifying the class in which they reside For example here are the prototypes of some methods from the Math class which is part of the javalang package static int abs int num static double cosdouble angle static double ceildouble num static double expdouble power static double powdouble num double power static double random static double sqrtdouble num Since these methods are static they do not need to be called on an object of the class Instead they are called by the class as follows Classnamemethodltparametersgt Here is an example SystemoutprintlnquotThe square root of 15 is quotMathsqrt15 All of these methods do NOT operate on an object but rather carry out some generic task like a C function Also note that all trig functions deal with angles in radians Math Class Example Quadratic Formula import javautil public class Quadratic public static void mainString args Scanner stdin new ScannerSystemin double a b c SystemoutprintlnquotEnter aquot a stdinnextDouble SystemoutprintlnquotEnter bquot b stdinnextDouble SystemoutprintlnquotEnter cquot c stdinnextDouble double disc Mathpowb2 4ac if disc lt O SystemoutprintlnquotComplex Rootsquot else double r1 bMathsqrtdisc2a double r2 b Mathsqrtdisc2a SystemoutprintlnquotRoots are quot r1 quot and quot r2 quotquot end if else end main end class Quadratic Reading Input from a File This is VERY VERY similar to reading in input from the keyboard You will still use a Scanner object But you must call it with a different constructor Scanner fin new Scanner new File quotinput txtquot In particular the input to the Scanner constructor must be a File object This File object can be created immediately by calling the File constructor that takes in an input le by its actual filename stored as a String From this point on all data from the le can be read using regular Scanner class methods we learned The only difference is that when a Scanner method is called the program won39t be quotwaitingquot for the user to input the data it will just read the next token from where it left off in the file To close a file do the following finclose In the example on the following page the user is prompted for the name of a le containing test scores The first line in the file will contain a positive integer n representing the number of scores in the file The following 11 lines will contain one integer each representing a single test score The program on the next page will open this file read in the values and calculate the average score of all the tests and output that to the screen Example Reading Test Scores from a File public class Tests public static void mainString args Scanner stdin new ScannerSystemin SystemoutprintlnquotEnter filequot String filename stdinnext Scanner fin int numvals new Scanner new Filefilename finnextInt double sum 0 for int i0 sum iltnumvals i finnextInt if numvals lt 0 SystemoutprintlnquotNo scoresquot else SystemoutprintlnquotAvg quot finclose sumnumvals quot quot Writing Output to a File This is also similar to standard output except that you have to set up a PrintStream object System0ut is already taken care of for you Here is the type of call to the constructor of PrintStream that is necessary PrintStream fout new PrintStream new Filequotoutputtxtquot This opens a new file quotoutputtxtquot to write to To write to the designated le just use the PrintStream object created and the methods in the PrintStream class such as println print and printf foutprintlnquotFirst line of the filequot When you are done writing to the file it should be closed as follows foutclose The example on the following page reads in a file with the same format as the previous example and writes out a new file in the same format with a adjusted scores for all scores in the file using the following formula New Score int50 5Old Score Example Writing out Adjusted Test Scores public class TestsZ public static void mainString args Scanner stdin new ScannerSystemin SystemoutprintlnquotEnter filequot String filel stdinnext Scanner fin new Scanner new Filefile1 SystemoutprintlnquotEnter outfilequot String file2 stdinnext PrintStream fout new PrintStream new Filefile2 int numvals finnextInt foutprintlnnumvals for int i0 iltnumvals i double newscore 505finnextInt foutprintlnintnewscore finclose foutclose Exceptions and File IO COP3330 Fall 2006 University of Central Florida H Schwartz Outline 0 An Exception throws try catch 0 finally 0 Creating Exceptions File output Co 3330 Fall 2006 An Exception runtime abnormal event Examples array index out of bounds dividing by zero trying to open a nonexistent file Co 3330 Fall 2006 An Exception E ile file new E ile exampletxt Scanner can be used 39 files as well Scanner fIn new Scannerfile could cause E ileNoteE oundExCeption if file doesn t exist fInnextIntcould cause IOEXception if there is not an int next How to handle throw allow the exception try 7 catch handle gracefully Co 3330 Fall 2006 throws public static void main String 1 args throws FileNOtEoundEXCeytion E ile file new E ile exampletxt Scanner fIn new Scannerfile could cause E ileNoteE oundException if file doesn t exist Allows a method to throw the exception A warning to others that the method may do this 7 leaves handling to others Co 3330 Fall 2006 trycatch Handle the exception without causing a runtime error Continue running Program exits due to code E ile file new Filestdinnext Scanner can be used with files as well Tangent Standard Error Stream Scanner fIn new Scannerfile catch FileNotE oundException e Systemerrprintlnfi e could not be found lt Systemexit0 terminates running the program Co 3330 Fall 2006 trycatch You may have multiple catch blocks for one try block int a 0 try int n fInnextInt int d fInnextInt a n d catch InputMismatchException e the input was the wrong type catch NoSuchElementException e ere was no more input to get catch ArithmeticException d was probably 0 and the division caused an error Co 3330 Fall 2006 finally always run after a try catch from example on previous page catch ArithmeticException e d was probably 0 and the division caused an error finally a 0reset a to 0 Co 3330 Fall 2006 Creating Exceptions An Exception is actually a class must extend Exception public class WeirdException extends Exception private String secondaryMessage public WeirdExceptionString str constructor for WeirdException takes in a string superstrpasses the string to Exception thisseco cor 3330 Fall 2006 Creating Exceptions To throw at any given point throw is a keyword follow with an Object which is an Exception throw new WeirdException something weird happened cor 3330 Fall 2006 Writing to a file 0 Many options 0 One of the easiest FileWriter 7 Inherits Writer and methods 0 writeString str int off int len writeString str 0 appendCharSequence csq Close Co 3330 Fall 2006 Writing to a file Constructors e FileWriterString fNamenonappend mode 7 FileWriterString file boolean bb indicate wheter to append open in append mode FileWriter fWrt new FileWriterfileName true fWrtwritequotHello World 39V fWrtclose write throws IOException Co 3330 Fall 2006


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.