Session 9 Lecture Notes for First Course in Java

(syllabus and calendar)

 

I/O - input and output

javadoc - documenting code - see ../javadoc/javadoc-info.htm


Interface as Data Type

Review of Exceptions

Upated Exceptions We Discussed

Final Exam We Discussed


[Optional: threads listing, and threads.zip - Chapter 11]


Applets

Quiz

Review for next week's final: an example of a final

final-08fall.zip has the Fall 2008 final with example

lecture9_2008.zip has examples for io, exceptions, applets, packages, javadoc, and the final

Hw6And7.zip homework examples

Final Exam2005-SUMMER.doc

Interface as Data Type

http://java.sun.com/docs/books/tutorial/java/IandI/usinginterface.html


Review of Exceptions

An exception is a non-normal condition that your code handles in a catch block. A finally block is for clean-up code that you want to happen at the end of method execution whether or not an Exception is thrown. Generally speaking, an exception can be thrown during execution of a try block. The finally block executes after execution leaves the try block, whether the cause of executing leaving the try block is no Exception was thrown and all the try block code has completed it execution, or an Exception was thrown and execution immediately left the try block.

Throws keyword: Checked and Unchecked Exceptions

Checked exceptions are certain Exceptions that that the compiler expects you, as programmer, to catch. These include input/output exceptions (IO Exceptions), NoSuchMethodException, ClassNotFoundException, and others listed in Table 9-3 (p. 355) of the textbook. If the method you defined MIGHT throw one of the checked exceptions AND the method does not have a Catch block for that exception, then the method must declare that is capable of throwing the exception:

void myMethod() throws NoSuchMethodException { ... }

This tells the Java Virtual Machine that if NoSuchMethodException is thrown during the execution of myMethod(), then the JVM should look for a catch block in the method that calls myMethod(), which might be main().

On the other hand, unchecked Exceptions are something that the compiler does not care about. For example, it is your choice whether to have a catch block for ArithmeticException [for divide by zero], ArrayIndexOutOfBoundsException [reference to an element beyond the length of the array], NegativeArraySizeException [setting the length to less than zero]. The compiler does not force you to handle these exceptions. If you do not write a catch block for the unchecked Exceptions, the JVM will automatically return the Exception message as the application fails (crashes). Other unchecked exceptions are listed in Table 9-2 (p.354).

Output is:

size = 3
length is: 3
size = 2
length is: 2
size = 1
length is: 1
size = 0
length is: 0
size = -1
ThomasException has been thrown.
ThomasException is ThomasException
Stack trace next
ThomasException
at DemoThomasExceptionSpecial.main(DemoThomasExceptionSpecial.java:25)
size = -2
Negative array java.lang.NegativeArraySizeException
Stack trace next
java.lang.NegativeArraySizeException
at DemoThomasExceptionSpecial.main(DemoThomasExceptionSpecial.java:27)


Let's look at how to catch an input/output exception when we want to read from a file.

All exceptions inherit from Throwable, so let's review Throwable

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html

public class Throwable
extends Object
implements Serializable

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

===============

Throwable provides two methods I want to point out:

getMessage

public String getMessage()
// returns the detail message string of this Throwable instance (which may be null).

toString

public String toString()
Returns a short description of this throwable. If this Throwable object was created with a non-null detail message string, then the result is the concatenation of three strings:

If this Throwable object was created with a null detail message string, then the name of the actual class of this object is returned.

===============

Let's look at Error

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Error.html

public class Error
extends Throwable

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

===============

Let's look at Exception

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Exception.html

public class Exception
extends Throwable

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

 ===============

 System.out.println(" The exception message is " + e.getMessage() + " and the exception string is " + e.toString());
===============

  1. What causes the ArrayIndexOutOfBounds exception?
  2. Is Throwable a class or an interface? What is the advantage of having it be the way it is?
  3. What is the difference between an Error and an Exception?

Stack Trace

A stack trace can help you debug your code. It indicates what happened before the exception occurred. It can be useful for debugging because it indicates the series of method calls, and even specific lines of execution, the precede the exception being thrown.


Possible Logic for try block with throw

try
  {
     if (coverage2.equals("liability"))
  {
  liabilityFlag = true;
  liabilityPremium = premium2;
  }
  else if (coverage2.equals("physicalDamage"))
  {
    physicalDamageFlag = true;
    physicalDamagePremium = premium2;
  }
  else
    throw
new CoverageException (coverage2);
  }
  catch (CoverageException e)
  {
    System.out.println("EXCEPTION is " + e.toString());
  }


Threads

Chapter 11, "Multithreaded Programming"


Applets

Example: animated blobs at http://www.mandrixx.net/javasimple.html

Sun's web site for applets: http://java.sun.com/applets/

Sun's tutorial on writing applets: http://java.sun.com/docs/books/tutorial/applet/overview/index.html
and includes a dog barking! http://java.sun.com/docs/books/tutorial/applet/appletsonly/sound.html

What is an applet?

A Java application, when the Java interpreter in the Java Virtual Machine executes the bytecode, is a normal program in native machine code that can make calls directly into the operating system and can access the file system.

An applet is more limited than an application.

http://java.sun.com/j2se/1.4.2/docs/api/java/applet/Applet.html
An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application.
The
Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer.
The
Applet class in part of a package called java.applet

A Java applet is something you can download and run as you surf the internet (or an intranet). An applet is limited to a "sandbox" for security: it runs inside of a browser, such as Netscape Navigator or Internet Explorer and cannot do things like copy your files to another computer. An applet is a virtual application that is locked inside another application, the browser.

A browser is a special application that interprets HTML, renders text and images, and can contain a version of the JVM. The applet runs inside the JVM of the browser.

The "sandbox" is a security layer around the applet that prevents the applet from harming you or your computer:
       http://java.sun.com/docs/books/tutorial/applet/overview/security.html

Each browser has a SecurityManager object that implements its security policies. When a SecurityManager detects a violation, it throws a SecurityException. Your applet can catch this SecurityException and react appropriately.
----------------------------------------------

(These restrictions can be customized by the client through the browser or by modifying the security properties file.)

Signed Applets

Signed applets are applets that are certified to come from a registered (and therefore hopefully trustworthy) source.

The provider of an applet can ask the end-user for permission to allow the applet out of the "sandbox" restrictions by signing the applet.

If the user's browser detects a signed applet, it displays the certificate and prompts the user to respond by trusting this applet, all applets from this applet provider, or declining to trust this applet.

To sign your applet, you work with a third party, such as VeriSign, http://www.verisign.com/products/signing/index.html
that provides a digital signature, or key, that authenticates you as the provider of the applet and guarantees that the applet code has not been alerted. 
VeriSign does not verify that the code in the applet is safe. VeriSign takes some business measures to attempt to verify that you are who you say you are. One such measure is accepting payment from you.

The client actually communicates both with the applet provider and the third party.

A signed applet has none of the applet restrictions, and is essentially an application even though it runs in the browser. Nevertheless, neither applets nor signed applets become the killer app of the internet. In general, applets are quite slow.

Is there any alternative to applets with limitations for security? Yes, the signed applet is an applet to which the end-user grants the same powers as an application. For example, the applet that installs the browser plug-in to update the browser JVM is a signed applet. VeriSign checks to make sure that it is Sun that offers the applet.

 

Your SDK provides a directory with demonstration applets. The path might be something similar to the following.
D:\java\j2sdk1.4.2_03\demo\applets


Suppose that I want to see one string inside a browser.
I need skeleton HTML that references the bytecode.

Here is the skeleton applet code.


This version has a Graphics object, which provides a sort of canvas against which text (and images) can be rendered by calling the paint method.

HelloWorld Applet in an HTML Page

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
    public void paint(Graphics g) {
        g.drawString("Hello world!", 50, 25);
    }
}

 

I can run this applet by opening the following HTML file in a browser:

<html>
   <head>
      <title>HelloWorld</title>
   </head>
   <body>
      <applet code="HelloWorld.class" width=200 height=100>
      </applet>
   </body>
</html>

I can name this HTML file HelloWorld.htm or any name I want.

This applet calls the drawString method of the Graphics class in the java.awt package, Java's earliest package for creating graphical user interfaces.

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html
public abstract void drawString(String str,
                                int x,
                                int y)

Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (xy) in this graphics context's coordinate system.

The Swing package is more recent than the awt package, but awt package has the advantage of being built-in to most browsers.

About Swing

The package is javax.swing and javax means java extended.

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/package-summary.html
Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

Swing's UIManager.setLookAndFeel method can be set for the native OS of the system, or for the look typical of Macintosh, UNIX, Windows, or Swing's own cross-platform look, which is called metal.

HelloWorld in the JDK's AppletViewer

 


The JDK (or SDK) contains a directory with sample applets.

Let's open the HTML file in for the fractal applet.

Applet Viewer

You can run an applet by using the lightweight applet viewer the comes with the JDK.
The applet viewer can help you debug and test your applet.
Later, you can write an HTML page that references the applet.

The applet viewer resides in the bin directory of your JDK.
On a Windows system, it might be:
D:\java\j2sdk1.4.2_03\bin\appletviewer.exe

You can launch an applet by giving the relative path to the HTML page for the applet. For example:

D:\java\j2sdk1.4.2_03\bin>appletviewer ..\demo\applets\Fractal\example1.html
which lauches the AppletViewer and runs a dynamic example:

Note: TextPad runs an applet with the appletviewer when you press Ctrl-3.

Here is another example:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\SimpleApplet.java

How does an applet run?

The differences between an applet and an application are that an applet:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java


This example has motion because it starts a thread to display a moving banner of text. A thread is similar to a process but a thread shares memory with the application that spawned it. A process runs in its own memory space. How does the object-oriented language, Java, create a thread object?

Here is the code:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java


Debugging an Applet

http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/appletviewer.html

-debug
Starts the applet viewer in the Java debugger, jdb, thus allowing you to debug the applets in the document.

You can debug applets using the -debug option of appletviewer. When debugging applets, it's best to invoke appletviewer from the directory that contains the applet's HTML file. For example, on the PC:
cd demo\applet\TicTacToe
..\..\bin\appletviewer -debug example1.html


More examples of the HTML necessary to run an applet.

Or:

Basic HTML to embed an applet in a web page

To embed an applet in a web page, you must write HTML code to reference the the applet's class file and the size of the applet.

Sun describes this at http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="MyApplet.class" width=100 height=140></applet>

Minimal HTML to display an applet

The glossary applet at http://www.wordesign.com/java/glossary/ uses very little HTML to display a glossary of Java terms:

<html>
<head>
<title>For the title bar of the browser's window--can be blank</title>
</head>
<body>
 some introductory text, if you want<br>
<APPLET CODE="com.yourCompany.yourProductPackage.YourApplet.class" height="80%" width="80%"></APPLET>
</body>
</html>

Note: The applet tag requires the fully qualified name of the class, which is the name of the class package followed by the class name.

HTML that references an applet in a package

If you declare in your java source code that your extension of the Applet class belongs to a package, your HTML page must reference the package as well as the class file.

(This also matches the file system because InPackage.class resides in a subdirectory called myappletpackage.)

And here's the HTML:


Creating an applet

To create an applet, you extend the Applet class and override methods of the java.applet package.

extending the applet class

Java defines the applet object in the java.applet package.

Key method definitions are:

Basic methods: init(), paint()

The init() method is called when the browser is done loading the applet. Using this method, you will typically any initializations that the applet needs.

An applet inherits the paint() method from the Component class. The paint() method takes as argument an instance of the Graphics class. The graphics object provides methods to draw geometric shapes and text.

For your first applet, you will typically override the paint() method to do your custom drawing.

Demonstration of an Applet

**********************************

Java Applet Example

import java.awt.Graphics;
import java.awt.Color;
public class HelloApplet extends java.applet.Applet {
	public void paint(Graphics g) {
		g.setColor(Color.red);
		g.drawString("Hello World!", 5, 50);
	}
}

Your HTML page references the applet's compile bytecode class name and defines the space for the browser display the running applet:

<HTML>
   <BODY>
      <applet code="HelloApplet.class" width=350 height=130>
      </applet>
   </BODY>
</HTML>

Parameters in the HTML page for an applet

passing parameters

You can pass parameters to an applet from the HTML code. 
For example, your HTML page might have a parameter, language, with a value, French, that tells the applet to display the French version of the applet.

The syntax to add parameters to your HTML page is:

http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="appletname.class" width=400 height=75>
 <param name="language" value="French"> 
 </applet>

How the applet gets parameter values from your HTML page

The applet class provides a method called getParameter() that takes as input a String that represents the name of the parameter. In our example, the parameter would be language. The return value of the getParameter() method is the value of the parameter. In our example, the parameter value is French.

size

The client can resize your applet if you specify the applet size as a percentage of the browser window. Alternatively, you can specify the applet size as a specific number of pixels.


Event Handling in an Applet

Graphical user interface's (GUI) are event-driven. They respond to the end-user's actions, such as clicking on buttons.
Java provides interfaces and classes to support event-driven programming.

http://java.sun.com/j2se/1.4.2/docs/api/java/util/EventListener.html

Two interfaces that support event-drive programming are MouseListener and MouseMotionListener.

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html

The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.)

The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseMotionListener.html

The MouseEvents applet handles mouse events as they occur.
This applet shows on the status bar the current position of the mouse, and also displays whether the mouse has entered or exited the applet area..

AppletViewer view (no HTML file specified):

Browser View (an HTML page opened):

Here's the code that monitors the actions of the mouse.

Sun provides this demonstration of event handling:

http://java.sun.com/docs/books/tutorial/applet/overview/componentMethods.html



Quiz

        REVIEW OF EXCEPTIONS:
  1. What causes the ArrayIndexOutOfBounds exception?
  2. Is Throwable a class or an interface? What is the advantage of having it be the way it is?
  3. If you try to divide by zero, will you get an Error or an Exception, and what is its name?

       EVENTS AND APPLETS

  1. Does a signed applet have the same capabilities as an application?
  2. Every applet is a subclass of the _____________ class of the __________________ package.
  3. How come applets do not have a main() method?
  4. What is an event?
  5. What reacts when an event occurs?