Java Programming Review Part II - PowerPoint PPT Presentation

About This Presentation
Title:

Java Programming Review Part II

Description:

E.g. IOException and SQLException are checked. Unchecked ... the last catch clause handles any kind of IOException. RuntimeException ... – PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 29
Provided by: jpv
Category:

less

Transcript and Presenter's Notes

Title: Java Programming Review Part II


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
These are built-inException classes
RunTimeException
SQLException
IOException
ArithmeticException
IndexOutOfBoundsException
FileNotFoundException
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 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 //
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
  • 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.

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 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

23
Example minimum balance
The BankAccountclass
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
  • 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

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
  • ArrayListltBankAccountgt accountswords.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 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 ) )

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 dont need
    even have to be named, although instances may be
    created
Write a Comment
User Comments (0)
About PowerShow.com