Download
lecture j the java api libraries n.
Skip this Video
Loading SlideShow in 5 Seconds..
Lecture J - The Java API Libraries PowerPoint Presentation
Download Presentation
Lecture J - The Java API Libraries

Lecture J - The Java API Libraries

206 Views Download Presentation
Download Presentation

Lecture J - The Java API Libraries

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Lecture J - The Java API Libraries Unit J1 - Exceptions

  2. Exceptions in Java • Java uses the notion of exception for 3 related (but different) purposes: • Errors: an internal Java implementation error was discovered • E.g: out of memory • Runtime exceptions: a programming logic error was discovered • E.g. division by 0 • Checked Exceptions: an exceptional case was discovered • E.g. file not found • Errors and Runtime exceptions will usually cause the program to crash • Checked exceptions should usually be handled by the programmer

  3. Occurrence of a runtime exception public class ExceptionExample { public static void main(String[] args) { int[] a = {2, 4, 6, 8}; for(int j = 0; j <= a.length ; j++) System.out.println(a[j]); } }

  4. Program Crash due to a runtime exception

  5. Runtime exceptions in the Java API • java.lang.ArithmeticException • java.lang.NullPointerException • java.lang.IllegalArgumentException • java.lang.NegativeArraySizeException • java.lang.ArrayIndexOutOfBoundsException • java.lang.ClassCastException

  6. Throwing a runtime exception public class Clock { private int hours, minutes, seconds; // constructors and methods public void setTime(int h, int m, int s){ if (h <1 || h>12 || m <0 || m>59 || s<0 || s>59) throw new IllegalArgumentException(); hours = h; minutes = m; seconds = s; } }

  7. Declaring a new runtime exception public class StackUnderflowException extends RuntimeException {} public class Stack { int elements[]; int top;//next empty location in the elements array // … constructor, push(), isEmpty() public int pop() { if (isEmpty()) throw new StackUnderflowException(); return elements[--top]; } } • The RuntimeException class has an empty constructor and one that accepts a string (denoting an error message).

  8. Checked Exceptions • Checked Exceptions denote exceptional situations that need to be dealt with. • They are dealt with by “catching” them • Using the try { … } catch { … } statement • Their possible occurrence in a method is considered part of the interface of the method • Must be declared using the throws keyword • Checked exceptions in the Java API: • java.net.ConnectException • java.io.IOException • java.io.EOFException • java.io.FileNotFoundException • java.util.TooManyListenersException

  9. Catching Exceptions import java.io.*; public class FirstLine { public static void main(String[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); } catch (IOException e) { System.out.println(“Problem: ” + e); } } }

  10. Throwing Checked Exceptions public class OverDraftException extends Exception { } public class BankAccount { private float balance; // constructors, fields, and methods public void withdraw(float amount) throws OverDraftException { if (amount > balance) throw new OverDraftException(); balance -= amount; } }

  11. Exception life-cycle • When a program performs an illegal operation the following happens: • The regular flow of the program stops • An exception object is created, which encapsulates the information about the problem that occurred • The method may try to catch and handle the exceptional situation • If the method ignores the exception the method execution ceases. • An exception then appears at the place in which the method was called • If the exception is not handled anywhere, the program crashes.

  12. Pumping up an exception public static void main(String[] args) { try { doWithdraws(); } catch (OverDraftException e) { callManager(); } } private static doWithdraws() throws OverDraftException { // Get list of withdraw orders for(/* iterate over withdraw orders */) bankAccount.withdraw(amount) } Overdraft! Hey, no one Catches this… I’ll crash the method!

  13. Declaring for exceptions • If a method must declare all the non run-time exceptions it may throw. • The declaration is done using the throws keyword • The user of the method is warned against possible exceptions that this method can throw • The exceptions that might be thrown by a method should also be documented with the @exception tag.

  14. Documenting Exceptions /** * Creates a Gate of a given type * @param type The type of the required gate * @return A Gate of the required type * @exception UnknownGateException If ‘type’ doesn’t * refer to a familiar gate. */ public Gate makeGate(String type) throws UnkownGateException { if (type.equals(“OR”)) return new OrGate(); if (type.equals(“AND”)) return new AndGate(); if (type.equals(“NOT”)) return new NotGate(); throw new UnknownGateException(); }

  15. Either catch // Called when the user chooses to add a gate private userAddsGate() { String type = //... look up the selected gate type try { Gate gate = makeGate(type); //... adds the gate to the model //... } catch (UnknownGateException uge) { // ignore this, don’t add the gate } }

  16. or declare // Called when the user chooses to add a gate private userAddsGate() throws UnknownGateException { String type = //... look up gate type Gate gate = makeGate(type); //... adds the gate to the model //... }

  17. Exceptions Hierarchy • All the classes for indicating run-time errors are derived from the class java.lang.Throwable. • The object you deliver to the throw statement must be an instance of class Throwable • The constructor of class Throwable initializes all the information about the location where the exception occurred, the state of the run-time stack etc. In this way this information is set for every exception object. • The following diagram explains the inheritance hierarchy for exceptions.

  18. Throwable class hierarchy Throwable Error Exception RuntimeException

  19. Multiple Catches import java.io.*; public class FirstLine { public static void main(String[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); } catch (FileNotFoundException e) { System.out.println(“File not found: “ + name); } catch (IOException e) { System.out.println(“Problem: ” + e); } } }

  20. finally • After all catches in a try-catch block, a finally clause may appear. • The finally section of code is executed before exiting from the try-block, whether or not an exception occurred. • The finally section is executed even if the try-catch block was exited by a return or break statement. try { // acquire resources // do stuff } catch (E1 e) { … } catch (E2 e) { … } finally { // release resources }

  21. Lecture J - The Java API Libraries Unit J2 - Streams

  22. Input / Output • A program often needs to communicate with other devices. In other words it should receive input and send output. • There are many types of input sources: • Reading a file from a local disk / diskette • Receiving a web page from a remote server • Receiving a communication message through a network. Receiving a signal from a sensor of a robot • Scanner, video camera, ... • Mouse, keyboard, joystick, ...

  23. Input / Output • Similarly, there are many types of output destinations: • Writing to a file on a local disk / diskette • Sending query information to a remote web server • Sending communication message to a remote host. Sending a command to a robot controller. • Printing a document to a printer / fax • Displaying graphics on the screen • ...

  24. GUI inputs and outputs • GUI related inputs and outputs are usually treated separately. They are given special API about which we will learn later. • GUI inputs and outputs include receiving mouse, keyboard and similar events, and displaying graphics on the screen.

  25. IO API - design goal • We want to make a distinction between the content of the data an application receives/sends and the source/destination of the data • The same kind of data can be stored on different types of media. • Similarly a given media can store different types of data.

  26. Scenario • Suppose we have an image processing application. It can read images, manipulate them and store them on a permanent storage. • We want our application to be able to read images from different types of sources: • local image files, remote images from the web, receiving an image from a scanner, ... • We want to be able to output the image to various types of destinations: • save the image to a local file, print the image on a printer, send the image to a fax recipient, ...

  27. Scenario Application

  28. IO Streams • We can achieve the separation by designing a common interface for reading any kind of data, and common interface for writing any kind of data. • This interface is implemented by the notion of input and output streams. • Any input can be represented as a sequence of bits. For convenience we divide the sequence into a sequence of bytes. • Similarly any output can be represented as a growing sequence of bytes.

  29. IO Streams 12 72 32 17 83 11 7 91 108 Input stream reading direction 43 55 31 37 34 13 17 1 15 Output stream writing direction

  30. Input streams • An input stream is a sequence of bytes that is attached to some input source. • You can read data from the stream in a sequential order. One byte at a time or several bytes at a time. • Input streams are represented by the abstract class java.io.InputStream. • Subclasses of InputStream defines input streams that are related to various data sources • Class InputStream gives a common interface for receiving data from various types of data sources

  31. Specific input streams InputStream . . . FileInputStream PipedInputStream ByteArrayInputStream

  32. Class InputStream • Class java.io.InputStream defines several methods that support the abstraction of allowing sequential reading from a stream: Reads the next byte from the stream. Return -1 if the end of the stream was reached. Reads up to b.length bytes from the stream into the array b. Returns the number of bytes that were read. public abstract int read() throws IOException public int read(byte[] b) throws IOException

  33. Input streams public int read(byte[] b, int offset, int length) throws IOException Reads up to length bytes from the stream into the array ‘b’ from the index ‘offset’. Returns the number of bytes that were read. Closes this input stream and releases any system resources associated with the stream. • Few additional methods (look up in the API) public void close() throws IOException

  34. Output streams • An output stream is attached to an output destination to which you can write data. • You can write data to the stream in a sequential order. One byte at a time or several bytes at a time. • Output streams are represented by the abstract class java.io.OutputStream. • Subclasses of OutputStream defines output streams that are related to various data destinations • Class OutputStream gives a common interface for sending data to various types of data destinations

  35. Specific output streams OutputStream . . . FileOutputStream PipedOutputStream ByteArrayOutputStream

  36. Class OutputStream • Class java.io.OutputStream defines several methods that support the abstraction of allowing sequential writing to a stream: Writes the specified byte (given as an int) to this output stream. Writes b.length bytes from the specified byte array to this output stream. public abstract void write(int b) throws IOException public void write(byte[] b) throws IOException

  37. Input streams public void write(byte[] b, int offset, int length) throws IOException Writes length bytes from the specified byte array starting at offset off to this output stream. Closes this output stream and releases any system resources associated with the stream. • Few additional methods (look up in the API) public void close() throws IOException

  38. Reading/Writing from/to files • java.io.FileInputStream is a subclass of InputStream that let you read a file (viewed as a sequence of bytes) • java.io.FileOutputStream is a subclass of OutputStream that let you write data to a file (as a sequence of bytes) • Both classes have constructors that get the path of the file as a parameter

  39. Writing to a file import java.io.*; class GenerateDiceData { static final int NUMBER_OF_TOSSES = 100000; public static void main(String[] args) { try { OutputStream output = new FileOutputStream(“dice.dat”); for (long i=0; i<NUMBER_OF_TOSSES; i++) { int randomThrow = (int)(Math.random()*6)+1; output.write(randomThrow); } output.close(); } catch (IOException ioe) { System.err.println(“Couldn’t write to file”); } } }

  40. Reading from a file import java.io.*; public class Count6Occurrences { static final int LOOK_FOR = 6; public static void main(String[] args) { long count = 0; try { InputStream input = new FileInputStream(“dice.dat”); int result; while ((result = input.read()) != -1) if (result == LOOK_FOR) count++; input.close(); System.out.println(count + “ occurrences”); } catch (IOException ioe) { System.err.println(“Couldn’t read from file”); } }}

  41. Downloading a file from the web page import java.io.*; import java.net.URL; // This program downloads a file from a given url // and saves it to the local file // Usage: java Download <url> <filename> public class Download { public static void main(String[] args) { try { download(args[0], args[1]); } catch (ArrayIndexOutOfBoundsException aioobe) { System.err.println(“Wrong usage.”); } catch (IOException ioe) { System.err.println(“Download failed”); } }

  42. Downloading a file from the web (cont.) // Downloads a remote file to the local disk. // source - The url of the remote file // filename - The name of the target file. private static void download(String source, String filename) throws IOException { InputStream input =(new URL(source)).openStream(); OutputStream output=new FileOutputStream(filename); int b; while ((b=input.read())!=-1) { output.write(b); } output.close(); } }

  43. Lecture J - The Java API Libraries Unit J3 - Readers and Writers

  44. Textual vs. binary data • We often make a distinction between textual data and other kind of data • We refer to files that stores text as ‘text files’ and to other files as ‘binary files’. • Binary files stores their information in various formats. In order to understand the content of a binary file you need to have a viewer that knows how to read the format the file is written with. • The structure of text files is more simple. It uses an encoding that gives a numeric code for each symbol and the text is stored as a list of numbers.

  45. Java & Unicode • One of the important aspects of Java is its platform independence • Therefore Java uses Unicode • However, most environments don’t support Unicode yet but only use ASCII. • Unicode uses two bytes per character while ASCII uses one byte • Java IO library overcomes this problem using Readers and Writers that translate between internal Unicode representation and external ASCII representation (with local extensions).

  46. Writers Writer writer = new FileWriter(“mail.txt”); writer.write(‘a’); writer.write(‘\u0590’); // Hebrew Aleph 97 1424 Automatic platform dependent translation made by the writer conversion to the platform specific code for aleph 97 224 standard ASCII no conversion needed 97 224

  47. Readers Reader reader = new FileReader(“mail.txt”); char c = reader.read(); // c = ‘\u0590’ c = reader.read(); // c = ‘a’ 97 1424 Automatic platform dependent translation made by the reader conversion from the platform specific code for aleph 97 224 standard ASCII no conversion needed 97 224

  48. Readers & Writers • java.io.Reader is an abstract class that defines a common interface for reading textual data • It is the counterpart of InputStream • You can read from a reader characters in a sequential manner. One character at a time, or several characters at a time. • Similarly, java.io.Writer is an abstract class that defines a common interface for reading textual data. • It is the counterpart of OutputStream

  49. Specific readers Reader . . . FileReader PipedReader CharArrayReader StringReader

  50. Specific writers Writer . . . FileWriter PipedWriter CharArrayWriter StringWriter