Java Review Slides Part II (updated!)
Download
Report
Transcript Java Review Slides Part II (updated!)
Java Programming Review
(Part II)
Enterprise Systems
Programming
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
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
The try-catch statement
try
{
statement1;
statement2; // if exception occurs here,
// statement3 will be skipped
statement3;
}
catch ( ExceptionClass e )
{
statement4; // executed after exception occurs
}
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
Some Java Exception classes
Exception
RunTimeException
ArithmeticException
SQLException
IndexOutOfBounds
Exception
These are built-in
Exception classes
IOException
FileNotFound
Exception
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
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
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
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…
}
// …
}
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
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
Try-catch chain
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
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 …
}
…
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
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
}
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
Text files
To write to a text file
1.
2.
3.
4.
Create it.
Write to it
(repeatedly).
Flush it (optional)
Close it.
To read from a text
file
1.
2.
3.
Open it.
Read from it
(repeatedly).
Close it
Assumes the file
exists.
Writing to text files
Create the text file
Write to the text file
f.println(…); // use like System.out
Can be repeated.
Close the file before exiting the program
PrintWriter f = new PrintWriter( “filename.txt” );
This opens the file.
File is initially empty.
f.close(); // ensures contents are updated
If you want to update the file without closing it
yet, you can call f.flush();
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();
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
Class-level (static) fields and methods
Built-in constants or objects
Built-in functions
Math.sqrt(), Math.abs(), Integer.parseInt()
Static methods
Math.PI, Color.green, System.out
public static void main( String[] args )
Static fields
your own constants
public static final int MY_CONSTANT
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
Example: minimum balance
The BankAccount
class
minBalance
100.00
There is one copy of
minBalance for the
whole class and shared
by all instances.
instances of the BankAccount class
SV129
balance
908.55
SV506
balance
1304.98
SV008
balance
354.00
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()
Useful for functions
It is not meant be invoked on an instance. It belongs to
the class.
e.g., Math.sqrt( double d )
Note: these methods cannot refer to instance variables
can only use static fields and methods
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
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<BankAccount> accounts;
words.add( new BankAccount( 1000 ) );
System.out.println( s.get( 0 ).getBalance() );
Parameter to add() must be a BankAccount object
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<int> numbers; is not
allowed but ArrayList<Integer> numbers; is fine
Auto-boxing makes use of wrapper classes more
convenient: numbers.add( 1 );
instead of numbers.add( new Integer( 1 ) );
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