Essay
Learning Java, Part 15: Applets, Events and the Remaining Keywords
Study notes on what applets were and why they are gone, the delegation event model with sources, listeners and event objects, adapter classes, and the keywords transient, volatile, instanceof, strictfp, assert and native. Written entirely by an AI model.
Schildt’s last three chapters move from the language to graphical programs. CITS2005 is unlikely to examine them, but two ideas from this chapter outlast the technology: the event model, which Swing, JavaFX, Android and web browsers all use, and a handful of keywords that every Java programmer should recognise.
Applets, and why they are gone
An applet was a small Java program that ran inside a web page, in a browser plug-in. It had no main. Instead, the browser called lifecycle methods on a subclass of java.applet.Applet:
| Method | Called when |
|---|---|
init() |
the applet is first loaded |
start() |
it becomes visible, or the page is revisited |
paint(Graphics g) |
it must redraw itself; you call repaint() to request this |
stop() |
the page is left |
destroy() |
it is removed from memory |
// not run: the java.applet package no longer exists in current JDKs
import java.applet.Applet;
import java.awt.Graphics;
public class Banner extends Applet {
public void paint(Graphics g) {
g.drawString("Hello from 2005", 20, 20);
}
}
Browsers dropped Java plug-ins in the late 2010s for security reasons. The applet API was deprecated in Java 9 and has now been removed: on a current JDK, the example above fails with “package java.applet does not exist”. Read this section for history and for the lifecycle idea, which survives in Android activities and in JavaFX’s Application (Part 16). Web front ends are now written in JavaScript or compiled to WebAssembly, which you will meet in CITS5505.
The delegation event model
A graphical program does not run top to bottom. It waits, and reacts when the user does something. Java organises this with three roles:
- An event source is the component where something happens: a button, a text field, a window.
- An event object describes what happened:
ActionEvent,MouseEvent,KeyEvent. They all descend fromjava.util.EventObject, which records the source. - A listener is an object that wants to know. It implements a listener interface, such as
ActionListenerwith its one methodactionPerformed(ActionEvent e), and registers with the source by callingaddActionListener(listener).
When the event happens, the source calls the method on every registered listener. The source “delegates” the handling to them, hence the name. This is the observer design pattern, which CITS4401 covers.
The pattern needs no GUI to understand. Here is a hand-made source and listener in plain Java:
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
class OrderEvent extends EventObject {
final String tea;
OrderEvent(Object source, String tea) { super(source); this.tea = tea; }
}
interface OrderListener {
void orderPlaced(OrderEvent e);
}
class Counter { // the event source
private final List<OrderListener> listeners = new ArrayList<>();
void addOrderListener(OrderListener l) { listeners.add(l); }
void removeOrderListener(OrderListener l) { listeners.remove(l); }
void order(String tea) {
OrderEvent e = new OrderEvent(this, tea);
for (OrderListener l : listeners) l.orderPlaced(e);
}
}
public class Events {
public static void main(String[] args) {
Counter counter = new Counter();
counter.addOrderListener(e -> System.out.println("kitchen: brew " + e.tea));
OrderListener till = e -> System.out.println("till: charge for " + e.tea);
counter.addOrderListener(till);
counter.order("chai");
counter.removeOrderListener(till);
counter.order("green");
}
}
kitchen: brew chai
till: charge for chai
kitchen: brew green
Swing’s JButton.addActionListener works exactly like addOrderListener here.
Mouse events and adapters
MouseListener has five methods (mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited) and MouseMotionListener two more (mouseDragged, mouseMoved). Implementing an interface means writing all of them, even if you care about one. An adapter class, such as MouseAdapter, implements every method with an empty body, so you extend it and override only what you need. Because the listener interfaces have more than one method, they are not functional interfaces, so you cannot use a lambda for them.
The remaining keywords
transient
When an object is serialised (converted to bytes with ObjectOutputStream, to save or send it), fields marked transient are skipped. Use it for values that can be recomputed or must not be saved, such as a cached result or a password.
volatile
A volatile field is always read from and written to main memory, so a write by one thread is visible to every other thread straight away. Without it, a thread may keep using a cached copy and never see the change:
public class Volatile {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long spins = 0;
while (running) spins++; // without volatile, this loop may never end
System.out.println("worker stopped");
});
worker.start();
Thread.sleep(50);
running = false;
worker.join();
}
}
worker stopped
volatile solves visibility, not atomicity. count++ on a volatile field still loses updates in the race from Part 11. Use synchronized or an AtomicInteger for that.
instanceof
x instanceof Type is true if x refers to an object of that type or a subtype, and false if x is null. Part 7 showed the modern pattern form, if (x instanceof Dog d). In a switch, Java 21 also allows type patterns:
public class Patterns {
static String describe(Object o) {
return switch (o) {
case Integer i when i < 0 -> "negative int";
case Integer i -> "int " + i;
case String s -> "string of length " + s.length();
case null -> "null";
default -> "something else";
};
}
public static void main(String[] args) {
System.out.println(describe(-3));
System.out.println(describe(7));
System.out.println(describe("tea"));
System.out.println(describe(null));
System.out.println(describe(2.5));
}
}
negative int
int 7
string of length 3
null
something else
strictfp
strictfp once forced floating-point arithmetic to give identical results on every processor. Since Java 17 all floating-point arithmetic is strict anyway, so the keyword still compiles but does nothing, and the compiler warns that it is redundant.
assert
assert condition; or assert condition : message; checks something that should always be true. If it is false, an AssertionError is thrown. Assertions are off by default and are enabled with java -ea:
public class Asserts {
static int half(int n) {
assert n % 2 == 0 : "odd input " + n;
return n / 2;
}
public static void main(String[] args) {
System.out.println(half(7)); // with java -ea this throws AssertionError
}
}
3
Because they can be switched off, never use assertions to check user input or arguments of public methods. Use them for internal assumptions, and throw an exception for anything a caller can get wrong.
native
A native method has no Java body. Its implementation is in C or C++, linked in through the Java Native Interface (JNI). You will rarely write one; newer code uses the Foreign Function and Memory API (Java 22).
Exam-style checks
- Describe the three roles in the delegation event model, and how a listener is connected to a source.
- What is an adapter class, and why can’t a lambda be used for a
MouseListener? - What does
volatileguarantee, and what does it not guarantee? - Why must assertions never be used to validate arguments to a public method?
Where to practise
Extend the Events example: add a ClosingListener with a different event, and let a listener remove itself after one call. Then run the Asserts example with and without -ea to see the difference. If you want to see the history, the book’s banner applet can be rewritten as a small Swing program, which is the subject of Part 16.