Download presentation
Presentation is loading. Please wait.
Published bySuzan Floyd Modified over 9 years ago
1
Java Programming Review (Part II) Enterprise Systems Programming
2
Outline Java programs and packages Classes, fields, methods, objects Naming conventions Types, variables, parameters Arrays Inheritance, interfaces Exceptions Files and streams Static fields and methods Java core packages, collection classes Generics, auto-boxing Inner classes
3
Exceptions Exception: something unexpected that can occur in the execution of a program wrong number format NullPointerException ArrayIndexOutOfBoundsException divide by zero attempt to open a file that does not exist etc. Java provides a way to handle exceptions that are thrown: the try-catch statement
4
The try-catch statement try { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3; } catch ( ExceptionClass e ) { statement4; // executed after exception occurs }
5
Example String s; … int convertedValue; try { convertedValue = Integer.parseInt( s ); } catch( NumberFormatException e ) { convertedValue = 0; } // ensures that convertedValue has a value // even if s does not contain a valid number
6
Some Java Exception classes Exception RunTimeExceptionSQLExceptionIOException ArithmeticException IndexOutOfBounds Exception FileNotFound Exception These are built-in Exception classes
7
Categories of exceptions Checked At compile time, the compiler requires you to address these errors Likely to happen no matter how careful you are in coding Class will not compile if you have no error handling E.g. IOException and SQLException are checked Unchecked Class will compile even without error handling Result from mistakes in programming E.g. all RuntimeException classes are unchecked
8
Throwing your own exceptions Some methods of the classes you write may result in errors during execution One option: handle the error within that method by printing an error message Use an if-statement Can be annoying since the user of the method may get the message interspersed with other output Better alternative: throw exceptions so that the user of the method can decide how to deal with the error
9
Throwing your own exceptions in Java Exceptions are thrown from the method that could cause the exception What needs to be done Define a class that extends Exception In the method declaration, include a throws clause In the method body, include a throw statement where the exception occurs Users of the method now need to use a try-catch statement
10
Example public class Dictionary { //… public void addWord( String word, String definition ) throws DuplicateWordException { if ( getDefinition( word ) != null ) throw new DuplicateWordException(); // code to add dictionary entry here… } // … } public class DuplicateWordException extends Exception { // this class could be empty }
11
Example Dictionary d = new Dictionary(); try { d.addWord( “bat”, “mammal with wings” ); d.addWord( “cat”, “animal with whiskers” ); d.addWord( “bat”, “equipment used in baseball” ); d.addWord( “elephant”, “a large mammal” ); } catch( DuplicateWordException e ) { System.out.println( “Duplicate Word Error” ); } An exception will be thrown on this call
12
More on exceptions Can have a more elaborate exception class by defining exception/error details inside the class; for example: error message additional data about the error (in the example, the word that causes the duplicate to occur can be stored in the DuplicateWordException class) Different kinds of exceptions can be handled using a try-catch chain
13
Try-catch chain try { … file operations … } catch( FileNotFoundException se ) { … if file is not found … } catch( EOFException ee ) { … if no more data to read … } catch( IOException e ) { … for all other cases not yet covered … } … You can use a try-catch chain to catch specific exceptions Note that in the example the last catch clause handles any kind of IOException
14
RuntimeException Make the exception class extend RuntimeException instead of Exception whenever you do not want to require that the exception be caught The user of the method may or may not use a try-catch statement (try-catch is required for Exceptions) If not within a try-catch, the program aborts
15
Ignoring exceptions If you choose to ignore (or not catch) checked exceptions, you must declare that they will be thrown In this example, when a file-related exception does occur, a run-time error will result public static void main( String args[] ) throws IOException { … file operations not enclosed in a try-catch statement }
16
Files and Streams File: Unit of “secondary” storage as opposed to “primary” storage in memory Stores a sequence of bytes/characters Stream operations: read from stream, write to stream Associated with a filename Often organized under a directory hierarchy Text files and streams: contains readable text
17
Text files To write to a text file 1. Create it. 2. Write to it (repeatedly). 3. Flush it (optional) 4. Close it. To read from a text file 1. Open it. 2. Read from it (repeatedly). 3. Close it Assumes the file exists.
18
Writing to text files Create the text file PrintWriter f = new PrintWriter( “filename.txt” ); This opens the file. File is initially empty. Write to the text file f.println(…); // use like System.out Can be repeated. Close the file before exiting the program f.close(); // ensures contents are updated If you want to update the file without closing it yet, you can call f.flush();
19
Reading from a text file Open the text file FileReader reader = new FileReader( “file.txt”) Scanner in = new Scanner( reader ) Read from the text file String line = in.nextLine(); Can be repeated. Close the text file in.close();
20
The static keyword In Java, the keyword static is used to indicate that a field or method is at the level of the class Regular fields and variables reside or operate at the level of objects
21
Class-level (static) fields and methods Built-in constants or objects Math.PI, Color.green, System.out Built-in functions Math.sqrt(), Math.abs(), Integer.parseInt() Static methods public static void main( String[] args ) Static fields your own constants public static final int MY_CONSTANT
22
Static fields means that the field is shared by all instances of the same class aka class variable as opposed to an instance variable e.g., in BankAccount, balance is an instance variable – each instance has its own independent copy However, if all BankAccounts share a minimum balance value, we can make a static field for that
23
Example: minimum balance SV129SV506 SV008 balance 908.55 1304.98 354.00 minBalance 100.00 There is one copy of minBalance for the whole class and shared by all instances. The BankAccount class instances of the BankAccount class
24
Static methods Normally, a method applies to a particular instance b.deposit( 100); deposits 100 to a particular object (pointed to by variable b) A static method is a method that does not operate on a particular instance That’s why we call them using ClassName.methodName() It is not meant be invoked on an instance. It belongs to the class. Useful for functions e.g., Math.sqrt( double d ) Note: these methods cannot refer to instance variables can only use static fields and methods
25
Some Java core packages java.lang – basic classes (no need to import) java.util – data structure and collection classes java.io – files and streams java.math – math functions java.net – networking java.sql – JDBC java.awt – abstract windowing toolkit (GUI) javax.swing – platform-independent GUI Use javap java.packagename.ClassName to print class details
26
Generics Generics allow container/collection classes to be type specific Less used alternative: contents are of type Object, the topmost class in Java Example: array lists ArrayList accounts; words.add( new BankAccount( 1000 ) ); System.out.println( s.get( 0 ).getBalance() ); Parameter to add() must be a BankAccount object
27
Wrapper classes and auto-boxing Each of the primitive types have corresponding wrapper classes containing single fields of that primitive type int => Integer, double => Double, … If you need objects/object references instead of regular values, use these wrapper classes Example: ArrayList numbers; is not allowed but ArrayList numbers; is fine Auto-boxing makes use of wrapper classes more convenient: numbers.add( 1 ); instead of numbers.add( new Integer( 1 ) );
28
Inner classes In general, only one Java class is defined in a single.java file The hard rule: A.java file must contain exactly one public class Non-public classes can be defined in the same file, for use inside the file only Inner classes: classes defined inside a class or inside methods of the class Restricts use of these classes to a particular scope Anonymous classes: some inner classes don’t need even have to be named, although instances may be created
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.