Title: Java Programming Review Part II
1Java Programming Review(Part II)
- Enterprise Systems Programming
2Outline
- 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
3Exceptions
- 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
4The try-catch statement
- try
-
- statement1
- statement2 // if exception occurs here,
- // statement3 will be skipped
- statement3
-
- catch ( ExceptionClass e )
-
- statement4 // executed after exception occurs
5Example
- 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
6Some Java Exception classes
Exception
These are built-inException classes
RunTimeException
SQLException
IOException
ArithmeticException
IndexOutOfBoundsException
FileNotFoundException
7Categories 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
8Throwing 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
9Throwing 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
10Example
public class DuplicateWordException extends
Exception // this class could be empty
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 //
11Example
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
12More 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
13Try-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
14RuntimeException
- 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
15Ignoring 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
16Files 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
17Text files
- To write to a text file
- Create it.
- Write to it (repeatedly).
- Flush it (optional)
- Close it.
- To read from a text file
- Open it.
- Read from it (repeatedly).
- Close it
- Assumes the file exists.
18Writing 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()
19Reading 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()
20The 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
21Class-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
22Static 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 aninstance 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
23Example minimum balance
The BankAccountclass
instances of the BankAccount class
24Static 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 - Thats 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
25Some 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
26Generics
- 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
- ArrayListltBankAccountgt accountswords.add( new
BankAccount( 1000 ) )System.out.println( s.get(
0 ).getBalance() )
Parameter to add() must be a BankAccount object
27Wrapper classes and auto-boxing
- Each of the primitive types have corresponding
wrapper classes containing single fields of that
primitive type - int gt Integer, double gt Double,
- If you need objects/object references instead of
regular values, use these wrapper classes - Example ArrayListltintgt numbers is not allowed
but ArrayListltIntegergt numbers is fine - Auto-boxing makes use of wrapper classes more
convenient numbers.add( 1 )instead of
numbers.add( new Integer( 1 ) )
28Inner 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 dont need
even have to be named, although instances may be
created