PROGRAMMING IN JAVA
PROGRAMMING IN JAVA CSCI 2220
Popular in Course
Popular in ComputerScienence
This 58 page Class Notes was uploaded by Santos Fadel on Monday October 19, 2015. The Class Notes belongs to CSCI 2220 at Rensselaer Polytechnic Institute taught by Staff in Fall. Since its upload, it has received 70 views. For similar materials see /class/224861/csci-2220-rensselaer-polytechnic-institute in ComputerScienence at Rensselaer Polytechnic Institute.
Reviews for PROGRAMMING IN JAVA
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/19/15
Programming in Java CSCI2220 Excep ons Excep ons Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code execution that prevents the program from continuing Array out of bounds accesses Divide by zero Null pointers To name a few Exceptions allow us to handle these events automatically when they happen What are Exceptions An Exception is a Java class There are many subclasses of the Exception class each corresponding to a different type of error or abnormal event that we wish to handle Basic concept When one of these abnormal events occurs Java will throw an Exception This means that it will instantiate a subclass of the Exception class Whenever an Exception could possibly be thrown you must provide a mechanism for catching it in your code Throwing Exceptions Essentially throwing exceptions in Java is a way of terminating method execution early public class String public char charAtint index throws IndexOutOfBoundsException throw new IndexOutOfBoundsException return c Catching Exceptions Anytime that you call a method that has been declared as being able to throw an Exception you can catch the Exception using a trycatch block try String text text SystemoutprintlntextcharAt10 catchIndexOutOfBoundsException e Systemerrprintln Index out of boundsquot eprintStackTrace If an Exception is thrown inside of a try block the exception that is returned is fonNarded as an argument to the catch block where the Exception can be handled Catching Exceptions In most cases if a method can throw an Exception and you want to call it you must deal with it However if the Exception that the method throws is a subclass of the RunTimeException class then you do not need to explicitly catch the Exception this includes lndexOutOfBoundsException from the previous example If a RunTimeException is thrown and not caught Java will automatically abort the program and print the stack trace of the exception RunTimeException These are the subclasses of the RunTimeException class ArithmeticException ndexOutOfBoundsException NegativeArraySizeException NullPointerException ArrayStoreException ClassCastException IllegaIArgumentException SecurityException IlegalMonitorStateException IllegalStateException UnsupportedOperationException Dealing with Exceptions As we have seen if a method throws an Exception that is not a subclass of RunTimeException we are required to deal with it if using this method One way is by using a trycatch block as we have seen You can also indicate that the calling method throws the same Exception essentially forwarding the responsibility of catching the exception to the code that calls your method public void myMethod throws IOException calls a method that throws an IOException Multiple catch blocks Sometimes a method can throw more than one possible Exception or the try block could call two different methods that throw two different Exceptions try String text text SystemoutprintlntextcharAt10 int n Integerparselnt abcquot catchIndexOutOfBoundsException e Systemerrprintln Index out of boundsquot eprintStackTrace catchNumberFormatException e Systemerrprintln bad numberquot eprintStackTrace Multiple catch blocks Since all Exceptions are subclasses of the Exception class you can generalize catch blocks to accept multiple different types of Exceptions by using a super class try String text text SystemoutprintlntextcharAt10 int n Integerparselnt abcquot catchException e Systemerrprintln Something bad happenedquot eprintStackTrace The finally block Sometimes when you call a trycatch block an Exception could be thrown before some important code that needs to be run at the end of the try block The finally block can be used to run this code Even if an exception is thrown the finally block will always execute try String text text SystemoutprintlntextcharAt10 catchIndexOutOfBoundsException e Systemerrprintln Index out of boundsquot eprintStackTrace finally important code Reth rowing Exceptions You can rethrow an exception after catching it and processing it try String text text SystemoutprintlntextcharAt10 catchIndexOutOfBoundsException e Systemerrprintln Index out of boundsquot eprintStackTrace throw e If you rethrow an Exception you must specify that the calling method throws the Exception Excep ons What type of information can you get from Exception objects getCause getMessage printStackTrace Sub classes of Exception can be much more elaborate and contain more information if desired You can also define your own Exception class which must be a subclass of Exception or one of its subclasses Homework 3 Homework 3 is out Due February 16 Homework 2 extended to Friday 1155 PM Programming in Java CSC2220 Collections Java Collections Framework Consistent welldefined API for maintaining groups of objects in containers A set of interfaces and classes to represent containers that also include support for manipulation operations ie adding objects removing objects etc The framework also includes builtin methods that operate on containers such as sorting searching etc Somewhat Analogous to the STL framework in C Java Collections Framework Collection List Set SortedSet Collection Generic definition for a group of objects Provides definitions for basic operations such as adding objects removing objects etc SortedMap Interface hierarchy List Generic definition for a list of objects that includes support for positional indexing Set Generic definition of a set of objects which does not allow duplicate objects and has no explicit random access support Map Generic definition of your basic map object that maintains keyvalue mappings and provides support for accessing elements via their associated keys Important Points All interfaces in the framework support collections of the generic type Object As we have seen every class is a subclass of type Object and therefore any object of any class can be used with any instance of the Collections Framework Advantage Superfluous support for heterogeneous collections Disadvantage Need for typecasting all the time Could cause other class casting problems especially when dealing with the Set interface and the definition of a duplicate object More Important Points Should be an obvious point by now Application developers can make generic use of Collection List Set and Map without knowing or caring how they actually work Polymorphism at work we have seen this behavior already in our Factory assignment Implementations Each interface has a number of built in implementations that operate differently internally List ArrayList internally represented as resizable array Vector internally represented as resizable array LinkedList internally represented as linked list Set HashSet hash table TreeSet sorted Redblack tree also implements SortedSet Map HashMap hash table Hashtable hash table TreeMap sorted Redblack tree also implements SortedMap Note The Vector and Hashtable classes existed in a version of Java prior to the development of the Collections Framework They were later retrofitted for inclusion into the framework List example The Vector class You should look at the Java API on Sun s site for details on the methods available in the Vector class as well as the other classes in the Collections framework there are many As said before the Vector class works like a resizable array under the hood lnstantiated with some initial capacity can be custom defined If elements are added to the Vector that overflows the capacity the internal array is automatically resized by some customizable increment value instantiate a Vector with the default capacity Vector Vl new Vector initial capacity of 100 Vector v2 new VectorlOO initial capacity 100 and capacity increment of 100 Vector v3 new VectorlOO lOO Basic Vector functionality Here is a nonexhaustive list of things you can do with Vectors Vector v new Vector Access the capacity and size int availableSpaces vcapacity Vsize add an element at some position in the Vector shifts all objects to the right down vaddl someObject overwrite an element at some position vsetl someObject search for an element in the Vector int index VindexOfsomeObject remove an element at some specified position vremoveO Just like with Array objects if you attempt to access a position in the Vector that is outside of the range of its size an ArrayOutOfBoundsException will be thrown Sets All implementations of the Set interface should adhere to the rule that duplicate elements are not allowed in the Set In a more formal sense for any two objects in the set 01 and 02 o1equals02 should return false in each case By default all classes have an implementation of the equalsObject 0 method defined in the Object class This implementation is usually not very useful as it basically returns whether or not 01 02 You should override the equals method if you wish to get meaningful operation when using a class the implements the Set interface SortedSet example TreeSet A SortedSet is even more restricted than a Set in the sense that the objects must be represented in some logical order There are two ways to do this we will use the TreeSet class which implements SortedSet to demonstrate The TreeSet can be instantiated with the default constructor When this is done any objects added to the Set should implement the Comparable interface public interface Comparable int compareToObject o The compareTo method should return a negative value zero or a positive value if this is less than equal to or greater than 0 respectively SortedSet example TreeSet The TreeSet can also be instantiated with an object that implements the Comparator interface public interface Comparator int compareObject ol Object 02 boolean equals0bject o The compare function works similarly to the compareTo method in the Comparable interface as it should return a negative if 01 lt 02 a zero if they are equal and a positive value ifoi gt 02 When objects are then added to the TreeSet they are compared by passing them to the compare function of the Comparator Sets Additional Notes Since Java allows heterogeneous Collections one must be careful when adding elements to Sets If the object being added has an incompatible equals method a ClassCastException may be thrown Similarly this is the case with the SortedSets and the comparison methods Maps associate them user defined key objects Array or Vector 1 gt gt 3 object1 objeth object3 objectn The basic concept behind Maps is that instead of associated elements in the container with indexes of an array you can Map gt dog cat I 39 77 pig I last object1 object2 object3 objectn Maps Available methods in a Map putObject key Object value putAllMap map getObject key removeObject key Methods used to process elements in a Map Set keySet Set entrySet Collection values Iterators Java has built in iterator capability that allows you to step through any collection class one element at a time Assume that we have a Collection object o Iterator myIterator citerator whi1emyIteratorhasNext Object nextElement process object myIteratornext There is also a Listlterator interface which is a subinterface to the Iterator interface Listlterators can only be used with Lists and allow you to step backwards as well as fonvards through a List and also allows you to add objects and replace objects in the List Collections class The Collections class provides several static methods that can be used to operate on Collection objects These include methods for Sorting Searching Copying Shuffling Among others Again look at the Java API for more details on these methods Homework 4 Homework 4 is posted online Due February 23 at 1155 PM Homework 3 due tonight Programming in Java CSC2220 More HQ Serialization Data Streams We saw last time how to treat streams as either streams of bytes or streams of characters Sometimes we want an even higher level of abstraction and wish to read and write data to and from streams in the form of primitive data variables or entire class objects Save program state information to a file Send data variables to different threads processes or across network streams Many other examples Java has built in stream classes that automatically handle converting this information into the necessary raw bytes that a stream can use DatalnputStream DataOutputStream The DatalnputStream and DataOutputStream Classes respectively allow you to read and write primitive data types to input and output streams BufferedOutputStream bufStream DataOutputStream dataStream try bufStream new BufferedOutputStreamnew FileOutputStream fileoutquot dataStream new DataOutputStreambufStream dataStreamwriteInt5 catchIOException e Systemerrprintln Error writing to filequot finally try dataStreamclose bufStreamclose catchIOException e Systemerrprintln Error closing filequot DatalnputStream DataOutputStream DatalnputStream readBooleanO readByte readChar readDoubleO readFloat readlnt readLong readShort DataOutputStream has corresponding write methods ObjectlnputStream ObjectOutputStream Since usually our programs do not consist of only primitive data types we also may wish to read and write class objects to streams We can do this with the ObjectlnputStream and ObjectOutputStream In fact the ObjectlnputStream and ObjectOutputStream classes provide the same functionality as DatalnputStream and DataOutputStream except they also include support for reading and writing object data via readObject and writeObject methods Serialization Objects can only be written to a stream if they are of a class type that implements the Serializable interface Most built in classes in Java implement Serializable Serializable does not define any methods So in order to make a user defined class capable of being written to a stream usually you can just append implements Serializable to the class declaration and it will work Serialization A somewhat obvious stipulation of writing objects to streams is that not only does the class need to implement Serializable but all of the members of the class must also be Serializable If a member of the class is not Serializable it can be declared transient and when the object is written to a stream that member will be written with a value of null Homework 5 That s all for today Remember Homework 5 is due in one week Programming in Java CSC2220 Threads Threads What is a thread A flow of control in a program Up until now you have written programs that have only one single flow of control V th threads you can have many flows executing at the same time Example Consider your basic word processor You have just written a large amount of text and now hit the save button It probably takes a noticeable amount of time to save the new data to disk this is all done with a separate thread in the background V thout threads the application would appear to hang while you are saving the file and be unresponsive until the save operation is complete Creating Threads Java has a built in class Thread To create a new thread you can create a new Class that extends Thread and override the run method public class ThreadExample extends Thread private String data public ThreadExampleString data thisdata data public void run Systemoutprintln l am a threadquot Systemoutprintln l was given an argument data Running Threads Creating an instance of the previous class does not actually create the thread You must call the start method of the Thread class public class ThreadExampleMain public static void mainString args Thread myThread new ThreadExample my dataquot myThreadstart Systemoutprintln l am the main threadquot The call to myThreadstart creates a new Thread and schedules the run method of myThread to execute myThreadstart returns almost immediately The Runnable Interface There is also a way to create a Thread in Java without extending the Thread class You can implement the Runnable interface instead which defines one method public abstract void run This is particularly useful if you wish to create a Thread object but want to use a different base class than the Thread class public class RunnableExample extends SomeClass implements Runnable private String data public RunnableExampleString data thisdata data public void run Systemoutprintln l am a threadquot Systemoutprintln l was given an argument data The Runnable Interface In order to create a new Thread from an object that implements the Runnable interface you must instantiate a new Thread object with the Runnable object as its target public class RunnableExampleMain public static void mainString args RunnableExample myRunnableObject new RunnableExample my dataquot Thread myThread new ThreadmyRunnableObject myThreadstart Systemoutprintln l am the main threadquot Calling start on the new Thread object will create a new Thread and schedule the run method of the Runnable object to be executed Thread Scheduling The JVM chooses which thread to run according to a fixed priority algorithm Every thread has a priority between the range of ThreadMNPRORTY and ThreadMAXPRlORlTY By default a thread is instantiated with the same priority as the thread that created it You can change the priority using the setPriority method of the Thread class Threads with higher priorities are run to completion before Threads with lower priorities get a chance at CPU time The algorithm is preemptive so if a lower priority thread is running and a higher priority thread becomes runnable the high priority thread will preempt the lower priority one Thread Scheduling If threads with the same priority are waiting to execute an arbitrary thread will be chosen Once a thread gains control of the CPU it will execute until one of the following occurs Its run method exits A higher priority thread becomes runnable and preempts it Its time slice is up on a system that supports time clicing It calls sleep or yield When a call to yield is made the thread gives othre threads with the same priority a chance to gain the CPU If no other threads of the same priority exist the thread continues to execute When a call to sleep is made the thread sleeps for the specified number of milliseconds during which time any other thread can use the CPU Other Thread operations 0 join method A call to the join method on a specific thread will cause the current thread to block until that thread is completed public class ThreadExampleMain public static void mainString args Thread myThread new ThreadExample my dataquot myThreadstart Systemoutprintln l am the main threadquot myThreadjoin Systemoutprintln l won t print until myThread finishesquot Other Thread operations interrupt method A call to the interrupt method sets the threads status to interrupted This does not explicitly interrupt the thread but this status can be checked from within the thread to facilitate any type of operation interrupted method This method returns a boolean value indicating the interrupted status of the current thread A call to this method resets the status of the current thread to not interrupted The use of these two methods in combination can serve as a method of requesting that a thread yield sleep or terminate itself for example Synchronization Often times multiple threads are accessing the same resources concurrently Reading andor writing the same file Modifying the same objectvariable Etc In these cases you must be careful how you coordinate these operations so that the resources end up in a consistent and expected state Java has built in primitives to facilitate this coordination Synchronization Example ProducerConsumer example Note this example is taken mostly from the Java tutorial on threads httpiavasuncomdocsbookstutoriaessentiathreadsmultithreadedhtml Overview There are two threads a producer and a consumer that are both accessing the same object of type CubbyHoIe CubbyHoIe is a simple object that holds a single value as its contents The producer thread randomly generates values and stores them in the CubbyHoIe object The consumer then retrieves these values as they are generated by the producer Synchronization Example The Producer thread public class Producer extends Thread private CubbyHole cubbyhole private int number public ProducerCubbyHole c int number Ci cubbyhole thisnumber number public void run for int i O i lt 10 i cubbyholeputnumber i try sleepintMathrandom 100 catch InterruptedException e Synchronization Example The Consumer thread public class Consumer extends Thread private CubbyHole cubbyhole private int number public ConsumerCubbyHole c int number Ci cubbyhole thisnumber number public void run int value O for int i O i lt 10 i value cubbyholegetnumber Synchronization Example Problems When the producer produces a value it stores it in the CubbyHoIe and then the consumer is only supposed to retrieve it once and only once Depending on how the threads are scheduled The producer could for example produce two values before the consumer is able to retrieve one o The consumer could consume the same value twice before the producer has produced the next value If the producer and consumer are accessing the cubbyhole at the same time they could produce an inconsistent state or miss a produced value Synchronization Example Solution synchronization public class CubbyHole private int contents private boolean available false public synchronized int getint who public synchronized void putint who int value When a thread executes a synchronized method it locks the object of the method that has been called No synchronized methods can be called by another thread on that object until the object is unlocked Synchronization Example Synchronized methods stop the producer and consumer from modifying the CubbyHoIe at the same time however we still need to coordinate the producer and consumer threads so that they do not produce or consume out of order public synchronized int get while available false tryl wait for Producer to put value wait catch InterruptedException e available false notify Producer that value has been retrieved notifyAll return contents Synchronization Example wait and notifyA methods are used to release the lock on an object and notify waiting threads that they can reacquire control public synchronized void putint value while available true try wait for Consumer to get value wait catch InterruptedException e contents value available true notify Consumer that value has been set notifyAll Homework 6 Homework 6 will be posted on the web soon Due March 30 3 weeks from now Homework 5 due 1155 PM tonight
Are you sure you want to buy this material for
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'