Thursday, March 18, 2010

private constructor

http://www.javacoffeebreak.com/articles/designpatterns/index.html

No, this isn't a dating guide for the romantic Java developer, but an introduction to the singleton design pattern.

For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.

Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.

Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}

Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

Tuesday, March 16, 2010

java lessons


Learn Java, JSP and more
Tutorials based on
Examples

http://javalessons.com/

Java Lessons
Fundamentals
SE
Advanced
IO, JDBC, Threads, ...
JSP, Servlets
web applications, EE
Swing
SE
ME
cell-phone apps, ME
EJB
server-side components, EE
JSF
web apps user interface, EE
Eclipse , Tips
Recent additions or updates

LessonViewer animation

Try a simulation
Click to see animation showing our LessonViewer

Other topics
JavaScript Energy
Shortcuts :
Interfaces
Abstract classes
JDBC
Threads

Static
Calculations
Polymorphism
Constructors
The easiest way to learn Java software programming is from examples.
Examples save time and simplify what seems to be difficult.

Working examples are provided by means of applets. Our goal however is to teach you Java programming, not building applets per se.
The Fundamentals tutorial doesn't focus on Java Swing issues, which makes it easier for beginners. Java Swing is dealt with in the separate GUI tutorial.
Have fun !
Sun's tutorials, Java Almanac, IBM Java, Oracle Java


About the author
Contact us
Dutch customers,
in-company Java
Terms,conditions,disclaimer Known problems

JavaLessons.com

Copyright © 2000-2009 SEMM (NL) All rights reserved
Contents and graphics contained throughout this web site have been registered.
Javatm is a Sun Microsystems, Inc. trademark.

CIT 591 Swing Layout Examples
Fall 2004, David Matuszek

Source code for the following examples is available as SwingLayoutExamples.zip.

http://www.cis.upenn.edu/~matuszek/cit591-2004/Pages/layout-examples.html

FlowLayout
import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class FlowLayoutExample extends JApplet {

public void init () {
getContentPane().setLayout(new FlowLayout ());
getContentPane().add(new JButton("One"));
getContentPane().add(new JButton("Two"));
getContentPane().add(new JButton("Three"));
getContentPane().add(new JButton("Four"));
getContentPane().add(new JButton("Five"));
getContentPane().add(new JButton("Six"));
}
}

GridLayout
import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class GridLayoutExample extends JApplet {

public void init() {
Container c = getContentPane();
c.setLayout(new GridLayout(2, 4));
c.add(new JButton("One"));
c.add(new JButton("Two"));
c.add(new JButton("Three"));
c.add(new JButton("Four"));
c.add(new JButton("Five"));
}
}

BorderLayout (Applet)
import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class BorderLayoutExample extends JApplet {

public void init() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(new JButton("One"), BorderLayout.NORTH);
c.add(new JButton("Two"), BorderLayout.WEST);
c.add(new JButton("Three"), BorderLayout.CENTER);
c.add(new JButton("Four"), BorderLayout.EAST);
c.add(new JButton("Five"), BorderLayout.SOUTH);
c.add(new JButton("Six"), BorderLayout.SOUTH);
}
}

BorderLayout (Application)
import java.awt.*;
// import java.applet.*;
import javax.swing.*;

public class BorderLayoutExample2 extends JFrame {

public static void main(String[] args) {
BorderLayoutExample2 frame = new BorderLayoutExample2();
frame.doSomething();
}


void doSomething() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(new JButton("One"), BorderLayout.NORTH);
c.add(new JButton("Two"), BorderLayout.WEST);
c.add(new JButton("Three"), BorderLayout.CENTER);
c.add(new JButton("Four"), BorderLayout.EAST);
c.add(new JButton("Five"), BorderLayout.SOUTH);
c.add(new JButton("Six"), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);

}
}

Nesting Panels
import java.awt.*;
import javax.swing.*;


public class FunWithPanels extends JFrame {

public static void main(String[] args) {
FunWithPanels frame = new FunWithPanels();
frame.doSomething();
}

void doSomething() {
Container c = getContentPane();

JPanel p1 = new JPanel();
p1.setLayout(new BorderLayout());
p1.add(new JButton("A"), BorderLayout.NORTH);
p1.add(new JButton("B"), BorderLayout.WEST);
p1.add(new JButton("C"), BorderLayout.CENTER);
p1.add(new JButton("D"), BorderLayout.EAST);
p1.add(new JButton("E"), BorderLayout.SOUTH);

JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(3, 2));
p2.add(new JButton("F"));
p2.add(new JButton("G"));
p2.add(new JButton("H"));
p2.add(new JButton("I"));
p2.add(new JButton("J"));
p2.add(new JButton("K"));

JPanel p3 = new JPanel();
p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));
p3.add(new JButton("L"));
p3.add(new JButton("M"));
p3.add(new JButton("N"));
p3.add(new JButton("O"));
p3.add(new JButton("P"));

c.setLayout(new BorderLayout());
c.add(p1, BorderLayout.CENTER);
c.add(p2, BorderLayout.SOUTH);
c.add(p3, BorderLayout.EAST);

pack();
setVisible(true);
}
}

GridLayout

Java Notes

http://leepoint.net/notes-java/GUI/layouts/30gridlayout.html

GridLayout

GridLayout lays out components in a rectangular grid, where all cells are equal size.

GridLayout forces components to have the same size.
JPanel content = new JPanel(new GridLayout(2,2));
content.add(new JButton("Button 1"));
content.add(new JButton("2"));
content.add(new JLabel("")); // for empty cell
content.add(new JButton("This is button three"));

To Create a GridLayout

There are three constructors:
   p.setLayout(new GridLayout());  // One row.  Columns expand.
p.setLayout(new GridLayout(rows, cols));
p.setLayout(new GridLayout(rows, cols, hgap, vgap));
with the following int parameters: rows is number of rows, cols is number of columns, hgap is horizontal space between components (in pixels), and vgap is vertical space between components (in pixels).

For example, this creates a panel with a grid layout of 4 rows and 3 columns. There are 5 pixels of horizontal space between components and 10 pixels of space between vertical components.
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 3, 5, 10));
p.add(. . .);

To add Components to a GridLayout

Use the .add(. . .) method to add components to a container with a GridLayout. You do not (can not) use the row and column to tell where to add the components -- add them in starting at the top left and going across the row first.

Empty Cells

There is no way to leave a cell empty in a grid layout. Although it often works ok to leave the final cells empty, there are reports of problems, so you should fill out the last cells in the final row too. The easiest way to do this is to put an empty label in any cell you want to skip. Eg,
p.add(new JLabel(""));

Saturday, March 13, 2010

Array

  • http://www.janeg.ca/scjp/lang/arrays.html
  • arrays are Java objects
  • all Java arrays are technically one-dimensional. Two-dimensional arrays are arrays of arrays.
  • declaring an array does not create an array object or allocate space in memory; it creates a variable with a reference to an array
  • array variable declarations must indicate a dimension by using []
    Examples of valid array declarations: (JJ pg84)      String[]s;     String []s;     String [] s;     String [ ] s;       // extra white space ignored     String[] s;     String[   ] s;      // extra white space ignored     String s[];     String s [];     String s [   ];     // extra white space ignored              String[] s[];     String[][]s;     String s [] [  ];   // extra white space ignored 
  • declaring the size of the array with the following notation is illegal
        String[5] s;        // illegal declaration 
  • the standard convention for declaring arrays is:
        String[] s;         // one-dimensional array     String[][] s;       // two-dimensional array 

Initializing arrays

  • all arrays are zero-based
  • arrays must be indexed by int values or byte, short or char values (as these can be promoted to int) (JLS §10.4)
  • using a long index value to access an array causes a compile error
  • attempting to access an array with an index less than 0 or greater than the length of the array causes anArrayIndexOutOfBoundsException to be thrown at runtime (JLS §10.4)
  • since arrays are Objects they can be initialized using the new operator
  • when created, arrays are automatically initialized with the default value of their type
    String[] s = new String[100];   // default values: null boolean[] b = new boolean[4];   // default values: false int[] i = new int[10][10];      // default values: 0 
  • array references declared as members are initialized to null BUT array references declared in methods are not initialized
class TestArray  {     int[] arr;          // member declaration, initialized to 'null'      public static void main(String[] args) {         int[] arr1;     // reference variable 'arr1' not initialized                  // compiles ok         System.out.println("arr:" + new TestArray().arr);          // compile error         System.out.println("arr1: " + arr1);     } } 
  • as arrays are allocated at runtime, you can use a variable to set their dimension
        int arrSize = 100;     String[] myArray = new String[arrSize]; 
  • you can use curly braces {} as part of an array declaration to initialize the array
        String[] oneDimArray = { "abc","def","xyz" }; 
Note
  • Curly braces {} can only be used in array declaration statements.
    String[] s;     // illegal initialization     s = { "abc", "def", "hij");               int[] arr = new int[] {1,2,3};  // legal 
  • you can assign an array a null value but you can't create an empty array by using a blank index
           int[] array = null;             // legal     // illegal initialization     int[] array = new int[];         

Initializing two-dimensional arrays

  • the first dimension represents the rows, the second dimension, the columns
  • curly braces {} may also be used to initialize two dimensional arrays. Again they are only valid in array declaration statements.
        int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} }; 
  • you can initialize the row dimension without initializing the columns but not vice versa
        int[][] myArray = new int[5][];     // illegal     int[][] myArray = new int[][5];  
  • the length of the columns can vary
      class TestTwoDimArrays {     // initialize # of rows     static int [][] myArray = new int[3][];       public static void main(String[] args) {      myArray[0] = new int[3];   // initialize # of cols     myArray[1] = new int[4];   // in each row     myArray[2] = new int[5];      for(int i=0; i<3; i="0;" i="0;">     

Also see

Sun Tech Tip: Manipulating Java Arrays

Thursday, March 11, 2010

exception and assertion

http://www.javapassion.com/handsonlabs/javaexceptions/index.html
Java Exceptions and Assertions
Sang Shin, www.javapassion.com/javaintro
This hands-on lab takes you through the basics of using Exceptions and Assertions. Java programming language has a well-designed Exception handling framework, which helps developers separate their exception handlng logic from the business logic.
Expected duration: 75 minutes

Software NeededBefore you begin, you need to install required software (JDK and NetBeans IDE) on your computer as described here.
1007_javaexceptions.zip (download)
It contains this document and the lab contents
Download it and unzip in a directory of your choice
Change Log
Feb. 9th, 2007: Created
March 19th, 2007: Homework is added
Jan. 10th, 2009: NetBeans 6.5 is used
Lab Exercises
Exercise 1: Exception handling (30 minutes)
Exercise 2: Custom exceptions (30 minutes)
Exercise 3: Assertions (15 minutes)
Homework Exercise (for people who are taking Sang Shin's "Java Programming online course")
Exercise 1: Exception Handling
In this exercise, you are going to trigger and catch built-in exceptions through try-catch-finally block.
Catch a runtime exception - divide a number by zero
Catch multiple runtime exceptions
Experience various exceptions
ArrayIndexOutOfBoundsException
Call built-in methods of Exception class
(1.1) Catch a runtime exception
In this step, you are going to trigger a runtime exception by dividing a number by 0. First, you will see how the default handler that is provided by the Java runtime system catches the exception. You will then catch the exception yourself through try-catch.
0. Start the NetBeans IDE if you have not done so.1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter DivideByZero. (Figure-1.10 below)
Click Finish. Figure-1.10: Create DivideByZero project
Observe that the DivideByZero project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.2. Modify Main.java as shown in Code-1.11 below. The change is to generate an exception.
package dividebyzero;public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println(3/0); } }Code-1.10: Main.java3. Build and run the program
Right click DivideByZero project node and select Run.
Observe the result in the Output window of the NetBeans IDE. (Figure-1.12 below)
Exception in thread "main" java.lang.ArithmeticException: / by zero at dividebyzero.Main.main(Main.java:14)Java Result: 1Figure-1.12: Result of running the application4. Modify the Main.java as shown in Code-1.13 below. The change is to catch an exception through try-catch block. The code fragments that need to be added are highlighted in bold and blue colored font.
package dividebyzero;public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { try{ System.out.println(3/0); } catch(Exception e){ System.out.printf("Caught runtime exception = %s", e); } } }Code-1.13: Catch Exception exception type5. Build and run the program
Right click DivideByZero project node and select Run.
Observe the result in the Output window of the NetBeans IDE. (Figure-1.14 below)
Caught runtime exception = java.lang.ArithmeticException: / by zeroFigure-1.14: Catching the exception6. Modify the Main.java as shown in Code-1.16 below. The change is to use more specific Exception class, ArithmeticException in this case. The code fragments that need to be added are highlighted in bold and blue colored font.
package dividebyzero;public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { try{ System.out.println(3/0); } catch(ArithmeticException e){ System.out.printf("Caught runtime exception = %s", e); } } }Code-1.16: Catch ArithmetricException exception type7. Build and run the program
Right click DivideByZero project node and select Run.
Observe the result in the Output window of the NetBeans IDE. (Figure-1.17 below)
Caught runtime exception = java.lang.ArithmeticException: / by zeroFigure-1.17: Catching the exceptionSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/DivideByZero. You can just open it and run it. 8. For your own exercise, please do the following tasks:
Add a code fragement that divides a number by 0 inside the catch block and see what happens. return to top of the exercise
(1.2) Catch multiple exceptions
In this step, you are going to use multiple catch statements to catch an exception. If the first catch statement does not catch an exception, the next one will be tried.
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter MultipleCatch.
Click Finish.
Observe that the MultipleCatch project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-1.21. Study the code by special attention to the bold-fonted parts.
package multiplecatch;import javax.swing.JOptionPane;public class Main { public static void main(String[] args) { // Enter the following values and see what exception is caught. // 0, 4, character, try { String value = JOptionPane.showInputDialog(null, "Enter value:"); // Non-numerica value will result an NumberFormatException int divisor = Integer.parseInt(value); // If the divisor is 0, it will result in ArithmetricException System.out.println(3/divisor); } catch (NumberFormatException nfe){ System.out.println("Exception caught by this program: Enter numeric value."); } catch (ArithmeticException exc) { System.out.println("Exception caught by this program: Divisor was 0."); } System.out.println("After exception."); } }Code-1.21: Main.java3. Build and run the program
Right click MultipleCatch and select Run.
Observe Input dialog box appears.
Enter 0 in the field. (Figure-1.22 below)
Click OK.Figure -1.22: Enter 0
Observe the display message in the output window of the IDE. (Figure-1.23 below)
Exception caught by this program: Divisor was 0.After exception.Figure-1.23: Catching an exception
Right click MultipleCatch and select Run.
Observe Input dialog box appears.
Enter 4 in the field.
Click OK.
Observe the display message in the output window of the IDE. (Figure-1.24 below)
0After exception.Figure-1.24: Catching an exception
Right click MultipleCatch and select Run.
Observe Input dialog box appears.
Enter somecharacter in the field. (Figure-2.15 below)
Click OK. Figure-1.25: Enter characters
Observe the display message in the output window of the IDE. (Figure-1.26 below)
Exception caught by this program: Enter numeric value.After exception.Figure-1.26: Catching an exception
Right click MultipleCatch and select Run.
Observe Input dialog box appears.
Do not type anything in the field.
Click OK.
Observe the display message in the output window of the IDE. (Figure-1.27 below)
Exception caught by this program: Enter numeric value.After exception.Figure-1.27: Catching an exceptionSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/MultipleCatch. You can just open it and run it. return to top of the exercise
(1.3) Experience various exceptions
In this step, you are going to generate various exceptions and see how they get caught by the catch statements.
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter ExperienceExceptions.
Click Finish.
Observe that the ExperienceExceptions project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-1.31. Study the code by special attention to the bold-fonted parts.
import java.awt.Frame;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.FileInputStream;import javax.swing.ButtonGroup;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JRadioButton;public class Main extends JFrame implements ActionListener { private double[] a; private JRadioButton divideByZeroButton; private JRadioButton badCastButton; private JRadioButton arrayBoundsButton; private JRadioButton nullPointerButton; private JRadioButton negSqrtButton; private JRadioButton overflowButton; private JRadioButton noSuchFileButton; private JRadioButton throwUnknownButton; public Main() { // Create a JPanel and GridLayout JPanel p = new JPanel(); p.setLayout(new GridLayout(8, 1)); // Create buttons and add them to the panel ButtonGroup g = new ButtonGroup(); divideByZeroButton = addRadioButton("Divide by zero", g, p); badCastButton = addRadioButton("Bad cast", g, p); arrayBoundsButton = addRadioButton("Array bounds", g, p); nullPointerButton = addRadioButton("Null pointer", g, p); negSqrtButton = addRadioButton("sqrt(-1)", g, p); overflowButton = addRadioButton("Overflow", g, p); noSuchFileButton = addRadioButton("No such file", g, p); throwUnknownButton = addRadioButton("Throw unknown", g, p); getContentPane().add(p); } private JRadioButton addRadioButton(String s, ButtonGroup g, JPanel p) { JRadioButton button = new JRadioButton(s, false); button.addActionListener(this); g.add(button); p.add(button); return button; } // Trigger and catch various exceptions public void actionPerformed(ActionEvent evt) { try { Object source = evt.getSource(); if (source == divideByZeroButton) { a[1] = a[1] / a[1] - a[1]; } else if (source == badCastButton) { Frame f = (Frame) evt.getSource(); } else if (source == arrayBoundsButton) { a[1] = a[10]; } else if (source == nullPointerButton) { Frame f = null; f.setSize(200, 200); } else if (source == negSqrtButton) { a[1] = Math.sqrt(-1); } else if (source == overflowButton) { a[1] = 1000 * 1000 * 1000 * 1000; int n = (int) a[1]; } else if (source == noSuchFileButton) { FileInputStream is = new FileInputStream("Java Source and Support"); } else if (source == throwUnknownButton) { throw new UnknownError(); } } catch (RuntimeException e) { System.out.println("Caught RuntimeException: " + e); } catch (Exception e) { System.out.println("Caught Exception: " + e); } } public static void main(String[] args) { JFrame frame = new Main(); frame.setSize(150, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); }}Code-1.31: Main.java3. Build and run the program.
Right click ExperienceExceptions and select Run.
Observe dialog box appears.
Click any of the radio buttons. (Figure-1.32 below) Clicking a button will execute code fragement that generates an exception.Figure-1.32 below
Observe the display message in the output window of the IDE. (Figure-1.33 below)
Caught RuntimeException: java.lang.NullPointerExceptionFigure-1.33: Catching an exceptionSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/ExperienceExceptions. You can just open it and run it. 4. For your own exercise, please do the following tasks.
Try other buttons and observe the exceptions that are caught
Try to catch exceptions using more specific exception classes (over RuntimeException and Exception classes). return to top of the exercise
(1.4) ArrayIndexOutOfBoundsException
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter ListOfNumbers-ArrayIndexOutOfBoundsException.
Click Finish.
Observe that the ListOfNumbers-ArrayIndexOutOfBoundsException project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-1.41. Study the code by special attention to the bold-fonted parts.
package listofnumbersarrayindexoutofboundsexception;public class ListOfNumbersTest { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); list.writeList(); }}Code-1.41: Main.java3. Write ListOfNumbers.java.
package listofnumbersarrayindexoutofboundsexception;import java.io.*;import java.util.Vector;public class ListOfNumbers { private Vector victor; private static final int SIZE = 10; public ListOfNumbers() { victor = new Vector(SIZE); for (int i = 0; i < SIZE; i++) victor.addElement(new Integer(i)); } public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < (SIZE + 1) ; i++) System.out.println("Value at: " + i + " = " + victor.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Finally: Closing PrintWriter"); out.close(); } else { System.out.println("Finally: PrintWriter not open"); } } }}Code-1.42: ListOfNumbers.java4. Build and run the program.
Right click ListOfNumbers-ArrayIndexOutOfBoundsException and select Run.
Observe the display message in the output window of the IDE. (Figure-1.43 below)
Entering try statementValue at: 0 = 0Value at: 1 = 1Value at: 2 = 2Value at: 3 = 3Value at: 4 = 4Value at: 5 = 5Value at: 6 = 6Value at: 7 = 7Value at: 8 = 8Value at: 9 = 9Caught ArrayIndexOutOfBoundsException: 10 >= 10Finally: Closing PrintWriterFigure-1.42: ResultSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/ListOfNumbers-ArrayIndexOutOfBoundsException. You can just open it and run it. return to top of the exercise
(1.5) Call built-in methods of Exception class
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter CallExceptionMethods.
Click Finish.
Observe that the CallExceptionMethods project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-1.51. Study the code by special attention to the bold-fonted parts.
package callexceptionmethods;public class Main { public static void main(String[] args) { try { throw new Exception("My Exception"); } catch (Exception e) { System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } }}Code-1.51: Main.java3. Build and run the program.
Right click CallExceptionMethods and select Run.
Observe the display message in the output window of the IDE. (Figure-1.33 below)
Caught ExceptiongetMessage():My ExceptiongetLocalizedMessage():My ExceptiontoString():java.lang.Exception: My ExceptionprintStackTrace():java.lang.Exception: My Exception at callexceptionmethods.Main.main(Main.java:7)Figure-1.52: ResultSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/CallExceptionMethods. You can just open it and run it. return to top of the exercise
Summary
In this exercise, you learned how to capture built-in exceptions.
return to the top
Exercise 2: Custom exception
In this exercise, you are going to create and throw your own exception classes.
Create your own exception 1
Create your own exception 2
Create your own exception class hierarchy
Create your own exception class hierarchy compile error
finally construct
Ignore Runtime exception
Ignore Runtime exception 2
Rethrow different exception
(2.1) Create your own exception 1
In this step, you are creating your own exception class called MyException.
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter YourOwnException.
For Create Main Class field, accept the default value, yourownexception.Main that is provided by the IDE.
Click Finish.
Observe that the YourOwnException project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Modify the IDE generated Main.java as shown in Code-2.11. Study the code by special attention to the bold-fonted parts.
package yourownexception;class MyException extends Exception { public MyException() { } public MyException(String msg) { super(msg); }}public class Main { public static void f() throws MyException { System.out.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException { System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); } public static void main(String[] args) { try { f(); } catch (MyException e) { e.printStackTrace(); } try { g(); } catch (MyException e) { e.printStackTrace(); } }} ///:~Code-2.11: Main.java
3. Build and run the program
Right click YourOwnException and select Run.
Observe the result in the Output window of the IDE. (Figure-2.12 below)
Throwing MyException from f()MyException at Main.f(Main.java:18)Throwing MyException from g() at Main.main(Main.java:28)MyException: Originated in g() at Main.g(Main.java:23) at Main.main(Main.java:33)Figure-2.12: ResultSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/YourOwnException. You can just open it and run it. return to top of the exercise
(2.2) Create your own exception 2
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter YourOwnException2.
For Create Main Class field, enter HexToDec.
Click Finish.
Observe that the YourOwnException2 project node is created under Projects pane of the NetBeans IDE and IDE generated HexToDec.java is displayed in the editor window of the IDE.
2. Modify the IDE generated HexToDec.java as shown in Code-2.21.
import javax.swing.*;// This is my custom exceptionclass InvalidHexException extends RuntimeException {}class HexToDec { // This method throws a custom exception called InvalidException static int [] convertToInt(String hex) throws InvalidHexException { char currChar; int intEq[] = new int[hex.length()]; for (int i = 0; i < currchar =" hex.charAt(i);">= '0' && currChar <='9') { intEq[i] = currChar - '0'; } else if (currChar >= 'a' && currChar <='f') { intEq[i] = currChar - 'a' + 10; } else if (currChar >= 'A' && currChar <='F' ) { intEq[i] = currChar - 'A' + 10; } else { throw new InvalidHexException(); } } return intEq; } static int convertToDec(int intEq[]) { int result = 0; int mult = 1; //multiplier for (int j = intEq.length - 1; j >= 0; j--) { result += intEq[j]*mult; mult *= 16; } return result; } public static void main(String args[]) { String hex; int intEq[]; // Receive hex value from a user hex = JOptionPane.showInputDialog(null, "Input hex: "); try { // convertToInt() method will throw InvalidHexExceptions if // the value is not in a valid format intEq = convertToInt(hex); Integer dec = new Integer(convertToDec(intEq)); // Display the result JOptionPane.showMessageDialog(null, dec); System.exit(0); } catch (InvalidHexException e) { JOptionPane.showMessageDialog(null, "InvalidHexException is caught: Enter valid hex value"); } System.exit(0); }}Code-2.21: HexToDec.java
3. Build and run the program
Right click YourOwnException2 and select Run.
Observe that a dialog box appears.
Enter 0 in the input form field and click OK.
Observe that the value is OK.
Click OK to close the message box.
Right click YourOwnException2 and select Run.
Observe that a dialog box appears.
Enter some characters, Shin in this example, in the input form field and click OK. This will trigger an exception.
Observe an exception.
Right click YourOwnException2 and select Run.
Observe that a dialog box appears.
Enter some characters, -100 in this example, in the input form field and click OK. This will trigger an exception.
Observe an exception.
Solution: This exercise uo to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/YourOwnException2. You can just open it and run it. 4. For your own exercise, please do the following tasks:
Modify HexToDec.java so that when a negative value such as -100 is entered, trigger a different exception called NegativeValueEnteredException return to top of the exercise
(2.3) Create your own exception class hierarchy
In this step, you have two exception classes which are related as parent and child exception class.
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter CatchingExceptionHierarchy.
Click Finish.
Observe that the CatchingExceptionHierarchy project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.31. Study the code by special attention to the bold-fonted parts.
class MyParentException extends Exception {}class MyChildException extends MyParentException {}public class Main { public static void main(String[] args) { try { throw new MyChildException(); } catch (MyChildException s) { System.err.println("Caught MyChildException"); } catch (MyParentException a) { System.err.println("Caught MyParentException"); } }} Code-2.31: Main.java3. Build and run the program
Right click CatchingExceptionHierarchy and select Run.
Observe the display message in the output window of the IDE. (Figure-2.32 below)
Caught MyChildExceptionFigure-2.32: ResultSolution: This exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/CatchingExceptionHierarchy. You can just open it and run it. 4. For your own exercise, please do the following tasks:
Modify Main.java in which a subclass of the MyChildException class is created and throw an exception of the newly created exception class in the try block and capture it. return to top of the exercise
(2.4) Create your own exception hierarchy compile error
In this step, you are going to see a compile error when parent exception class is used before child exception class in the multiple catch statements structure.
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter CatchingExceptionHierarchy-CompileError.
Click Finish.
Observe that the CatchingExceptionHierarchy-CompileError project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.41. Observe the compile error. (Figure-2.42 below)
package catchingexceptionhierarchycompileerror;class MyParentException extends Exception {}class MyChildException extends MyParentException {}public class Main { public static void main(String[] args) { try { throw new MyChildException(); } catch (MyParentException s) { System.err.println("Caught MyParentException"); } catch (MyChildException a) { // Compile error expected System.err.println("Caught MyChildtException"); } }} Code-2.41: Main.javaFigure-2.42: Compile errorSolution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/CatchingExceptionHierarchy-CompileError. You can just open it and run it. return to top of the exercise
(2.5) Finally
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter FinallyWorks.
Click Finish.
Observe that the CatchingExceptionHierarchy project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.51. Study the code by special attention to the bold-fonted parts.
package finallyworks;class MyException extends Exception {}public class Main { static int count = 0; public static void main(String[] args) { while (true) { try { // Post-increment is zero first time: if (count++ == 0) throw new MyException(); System.out.println("No exception"); } catch (MyException e) { System.out.println("MyException"); } finally { // finally is always called System.out.println("In finally clause"); if (count == 2) break; // out of "while" } } }} Code-2.51: Main.java3. Build and run the program
Right click FinallyWorks project node and select Run.
Observe the display message in the output window of the IDE. (Figure-1.42 below)
MyExceptionIn finally clauseNo ExceptionIn finally clauseFigure-2.52: ResultSolution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/FinallyWorks. You can just open it and run it. return to top of the exercise
(2.6) Ignore Runtime exception
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter IgnoringRuntimeException.
Click Finish.
Observe that the IgnoringRuntimeException project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.61. Study the code by special attention to the bold-fonted parts.
package ignoringruntimexception;public class Main { static void someMethod2() { throw new RuntimeException("From someMethod2()"); } // Note that this method does not need to // catch the RunTimeException. static void someMethod() { someMethod2(); } public static void main(String[] args) { someMethod(); }} Code-2.61: Main.java3. Build and run the program
Right click IgnoringRuntimeException and select Run.
Observe the display message in the output window of the IDE. (Figure-2.63 below)
Exception in thread "main" java.lang.RuntimeException: From someMethod2() at ignoringruntimexception.Main.someMethod2(Main.java:7) at ignoringruntimexception.Main.someMethod(Main.java:13) at ignoringruntimexception.Main.main(Main.java:17)Java Result: 1Figure-2.63: Catching an exceptionSolution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/IgnoringRuntimeException. You can just open it and run it. return to top of the exercise
(2.7) Ignore Runtime exception 2
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter IgnoringRuntimeException2.
Click Finish.
Observe that the IgnoringRuntimeException2 project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.71. Study the code by special attention to the bold-fonted parts.
package ignoringruntimeexception2;class MyException extends RuntimeException { public MyException(String x){ super(x); }}public class Main { static void someMethod2() { throw new MyException("From someMethod2()"); } // Note that this method does not need to // catch the RunTimeException. static void someMethod() { someMethod2(); } public static void main(String[] args) { someMethod(); }} Code-2.71: Main.java3. Build and run the program
Right click IgnoringRuntimeException2 and select Run.
Observe the display message in the output window of the IDE. (Figure-2.72 below)
Exception in thread "main" ignoringruntimexception.MyException: From someMethod2() at ignoringruntimexception.Main.someMethod2(Main.java:13) at ignoringruntimexception.Main.someMethod(Main.java:19) at ignoringruntimexception.Main.main(Main.java:23)Java Result: 1Figure-2.72: Catching an exceptionSolution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/IgnoringRuntimeException2. You can just open it and run it. return to top of the exercise
(2.8) Rethrow different exception
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter RethrowDifferentException.
Click Finish.
Observe that the RethrowDifferentException project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Main.java as shown in Code-2.81. Study the code by special attention to the bold-fonted parts.
package rethrowdifferentexception;class OneException extends Exception { public OneException(String s) { super(s); }}class TwoException extends Exception { public TwoException(String s) { super(s); }}public class Main { public static void someMethod() throws OneException { System.out.println("originating the exception in someMethod()"); throw new OneException("thrown from f()"); } public static void main(String[] args) throws TwoException { try { someMethod(); } catch (OneException e) { System.err.println("Caught in main, e.printStackTrace()"); e.printStackTrace(); // The TwoException will be handled by default exception // handler. throw new TwoException("from main()"); } }} Code-2.81: Main.java3. Build and run the program
Right click RethrowDifferentException and select Run.
Observe the display message in the output window of the IDE. (Figure-2.82 below)
originating the exception in someMethod()Caught in main, e.printStackTrace()rethrowdifferentexception.OneException: thrown from f() at rethrowdifferentexception.Main.someMethod(Main.java:19) at rethrowdifferentexception.Main.main(Main.java:24)Exception in thread "main" rethrowdifferentexception.TwoException: from main() at rethrowdifferentexception.Main.main(Main.java:31)Java Result: 1Figure-2.82: ResultSolution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/RethrowDifferentException. You can just open it and run it. return to top of the exercise
Summary
In this exercise, you have learned how to create, throw, and catch your own custom exceptions. return to the top
Exercise 3: Assert
In this exercise, you are going to exercise Assert feature of Java programming language.
Build and run AssertExample program with Assert disabled first and then enabled
(3.1) Build and run AssertExample program
1. Create a NetBeans project
Select File from top-level menu and select New Project.
Observe that the New Project dialog box appears.
Select Java under Categories section and Java Application under Projects section.
Click Next.
Under Name and Location pane, for the Project Name field, enter AssertExample.
For Class Main Class field, enter assertexample.Diamond.
Click Finish. Figure-3.10: Create a new project
Observe that the AssertExample project node is created under Projects pane of the NetBeans IDE and IDE generated Diamond.java is displayed in the editor window of the IDE. 2. Modify the IDE generated Diamond.java as shown in Code-3.11. Study the code by special attention to the bold-fonted parts.
package assertexample;import javax.swing.*;class Diamond { static void printDiamond(int size) { String diamond = ""; /* print upper triangle */ for (int r = 1, a = 1; r <= size; r++, a+=2) { /* print spaces */ for (int i = size - r; i >= 1; i--) { diamond += " "; } /* print *'s */ for (int j = 1; j <= a; j++) { diamond += "*"; } diamond += "\n"; } /* print lower triangle */ for (int r = size - 1, a = 2*(size-1)-1; r >= 1; r--, a-=2) { /* print spaces */ for (int i = size - r; i >= 1; i--) { diamond += " "; } /* print *'s */ for (int j = 1; j <= a; j++) { diamond += "*"; } diamond += "\n"; } JOptionPane.showMessageDialog(null, diamond); System.out.println(diamond); } public static void main(String args[]) { String strSize; // Get the size of the diamond to draw strSize = JOptionPane.showInputDialog(null, "Enter diamond size:"); int size = Integer.parseInt(strSize); // Assert that the value entered is greater than 0, otherwise, // it will generate AssertionError exception. try { assert(size > 0); printDiamond(size); } catch (AssertionError e) { JOptionPane.showMessageDialog(null, "AssertionError is captured: Size should be > 0."); } System.exit(0); }}Code-3.11: Diamond.java3. Build and run the program without Assert enabled (which is the default)
Right click AssertExample project node and select Run.
Observe that an input dialog box appears. (Figure-3.12 below)
Enter a positive number, like 5.Figure-3.12: Enter diamond size
Observe that a diamond gets displayed.Figure-3.13: Display of the diamond
Right click AssertExample project node and select Run.
Observe that an input dialog box appears.
Enter a negative number, like -8.
Observe that a display with nothing gets displayed. (Figure-3.14 below)Figure-3.14: No diamond gets displayed
4. Run the program with Assert Feature enabled.
Right click AssertExample project and select Properties.
Observe that the Project Properties dialog box appears.
Select Run on the left and for the VM Options field, enter -ea. The -ea option indicates your intention of running the application with Assert feature enabled. (Figure-3.15 below)
Click OK.Figure-3.15: Enable Assert 5. Build and run the program again
Right click AssertExample project node and select Run.
Observe that an input dialog box appears.
Enter a negative number, like -5.
Observe that the Assert feature is now working. (Figure-3.16 below) Figure-3.16: Assert is now enabled.Solution: This step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as /javaexceptions/samples/AssertExample. You can just open it and run it.
6. For your own exercise, modify Diamond.java so that the a number that is greater than 20 generates AssertionError
Summary
In this exercise, you have learned how to use assert feature of Java programming language.
return to the top
Homework exercise (for people who are taking Sang Shin's "Java Programming online course")
1. The homework is to modify AssertExample project above as following. (You might want to create a new project by copying the AssertExample project. You can name the homework project in any way you want but here I am going to call it MyExceptionProject.)
Run the program without assertion so that you can catch user errors through exceptions.
If a user enters a negative value, throw a MyOwnNegativeValueEnteredException, which is an extension of ArithmeticException. The display of the error information should display the negative number that was entered.
If a user enters zero, throw a MyOwnZeroValueEnteredException, which is an extension of ArithmeticException.
2. Send the following files to javaprogramminghomework@javapassion.com with Subject as JavaIntro-javaexceptions.
Zip file of the the MyExceptionProject NetBeans project. (Someone else should be able to open and run it as a NetBeans project.) You can use your favorite zip utility or you can use "jar" utility that comes with JDK as following.
cd (assuming you named your project as MyExceptionProject)
jar cvf MyExceptionProject.zip MyExceptionProject (MyExceptionProject should contain nbproject directory)
Captured output screen - name it as JavaIntro-javaexceptions.gif orJavaIntro-javaexceptions.jpg (or JavaIntro-javaexceptions.)
Any screen capture (just one of them) that shows that your program is working is good enough. No cosmetic polishment is required.
If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.

assertion and exception

http://geekexplains.blogspot.com/2008/06/asserions-in-java-assertions-vs.html

Asserions in Java? Assertions vs Exception? Where to Use & Where NOT?Assertion in JavaAn assertion is a special statement which contains one boolean expression and if that boolean expression returns 'false' then the program throws an AssertionError which is an unchecked exception and it normally terminates the current program/application.This boolean expression is normally used to verify our assumptions which we used while designing our application. Thus, assertions can be used to write correct programs i.e., the programs which run in accordance with their specifications. Assertions can be easily enabled or disabled (by defauly they are disabled) and this greatly helps improving the maintainability of the application.An assertion statement can have two forms in Java:-

assert BooleanExpression; - AssertionError is thrown if BooleanExpression is false.
assert BooleanExpression : ExpressionReturningSomeValue; - in this case the returned value of ExpressionReturningSomeValue is paased to the constructor of the AssertionError class, which is inturn used to provide a String representation of this value as the detailed error message which caused this AssertionError. Remember that the second expression should should always return some value, so we can't use a method call whose return type is void. For all other return types (separate ones for all primitive types and Object type for all reference types and Arrays) the AssertionError class has separate overloaded constructors which are called based on the type of the passed parameter.Where assertions should NOT be used?Assertions should never be a part of the implementation of some functionality of the application. They should only be used to verify the assumptions - just to be sure that whatever we assumed while desinging the solution is actually valid in practical as well. Below are few situations where you may get tempted to use assertions, but you should NOT use them:-
Do NOT use assertions to implement any application functionality - enabling/disbaling them may cause servere damage to the state of the application and its usability.
Do NOT use assertions for argument checking of public methods - public methods represent the public interface of the underlying class to the outside world and the methods should always behave the same. If we use assertions for argument checking then enabling or disabling assertions may change the behavior of the method dramatically, which is of course highly undesirable. In addition, using assertions in such cases won't give us actual cause of the error as it can only throw AssertionError (with a message) and it's obviously not as good as getting the actual cause like IndexOutOfBoundsException, NullPointerException, IllegalArgumentException, etc., which we will otherwise get if we check the arguments without using assertions.Where to use Assertions?As we know that assertions should be used to test the assumptions so that we can guarantee a correct program. Hence, they should be used at the places where the execution assumes something and proceeds accordingly. Few of such scenarios are:-
Implementing Pre-conditions - assertions can be used to effectively implement pre-conditions. A pre-condition means something which must be true at the time of invokation of a method (otherwise the method may go erratic). An example of such a pre-condition can be checking whether the current thread holds (or doesn't hold) a lock on an object before the thread actually executes a method.
Implementing Post-Conditions - similar to Pre-Conditions, these are the assumptions which are expected to be true once the control returns from a method. Assertions can be used effectively to check if it's actually as per the assumption or not. If not then it's better to stop the execution and terminate the application as proceeding further in such a scenario may lead the application to an inconsistent state.
Implementing Class Invariants - assetions can be used effectively to check if the assumed relationship between various members of a class is intact or not. This especially helps when an instance is in transition from one consistent state to another and using an assertion to confirm before proceeding further will reduce the possibility of having the application in an inconsistent state.Assertion vs ExceptionWe just discussed that assertions should be used to verify the assumptions so that we can guarantee that the application always executes complying with the specifications. Thus we see that assertion is basically a mechanism which helps us writing correct programs. Whereas Exception is a mechanism of checking if the implementation is executing without any expected or unexpected errors or not. So, we see that exceptions are basically used for handling even the unforseen conditions during the execution of an application in a better way and hence using exceptions effectively results into a robust application.Just visualize the difference between something being correct and something being robust. 'correct' obviously means that whenever the application runs, it runs correctly in accordance with specs whereas 'robust' means whenever the application encounters an error condition either expected in case of checked expection OR unexpected in case of unchecked exceptions, it always handles the execution in a controlled way - either by ignroing the exception or by handling the exception (maybe by saving the state and terminating gracefully).Therefore, we see that assertions and exceptions are not rivals. In fact they are complimentary to each other and an effective combination of both can ensure the development of a correct and robust application.