Introduction to Java
Standalone applications - Windows 95+, UNIX/X, Macintosh
- General programming language except for low level (nonportable)
access (through native C/C++ methods)
- Compiled to interpreted bytecode (virtual machine)
- Requires JRE (Java Runtime Environment) to run
- Hello.java is a standalone program that prints
Hello world
Applets - IE 3.0+, Netscape 3.0+, Hotjava
- Run in an HTML page
- Cannot read or write local files
- Cannot start local process
- Cannot communicate over network except to server
- HelloApplet.html contains an applet
that prints Hello world
Availability
Language
- Object oriented - data abstraction, inheritance, polymorphism
- Standard GUI and network interfaces
- Garbage collection
- Threads
- Run-time safety - exception handling
Versions
- Java 1.0 - 1995
- 4+1 MB download (JDK and docs)
- Netscape 3.0 or IE 3.0
- 8 standard packages
- Supports .gif, .jpeg images, .au sounds
- Java 1.1 - 1996
- 9+4 MB download
- Netscape 4.0 or IE 4.0
- JIT compiler (faster execution)
- .jar files (faster download)
- new event handling model
- inner classes
- internationalization (read/write Unicode text,
date and number formats)
- serialization (save, load objects)
- reflection (class Class)
- Java Beans (for GUI editors)
- JDBC (database support)
- RMI (remote method invocation)
- Security (encryption and digital signatures)
- Java 2 (aka Java 1.2) - 1999
- 20+17 MB download
- Performance improvements (faster)
- Swing (new GUI with programmable look and feel)
- Java-2D advanced graphics
- Drag and drop to/from non Java programs
- Collections (set, list, map)
- CORBA (object transfer)
- Supports .wav, .midi, .aiff, .rmf sound files (and .au)
Examples
- Wc.java illustrates file I/O and exceptions.
- Unique.java illustrates several useful
data structures (String, List, Vector, Hashtable, Stack) and
polymorphism.
- Clock applet illustrates threads and animation.
- wget.java illustrates reading a webpage.
- wget2.java reads webpage including header.
- telnet.java illustrates network
communication and threads (Java 1.1).
- Webserver.java illustrates an HTTP server.
- Edit.java illustrates, menus, dialogs, and
file I/O.
Java vs. C++
- No preprocessor (#include, #define)
- No global variables (class members and local variables only)
- No global functions (methods only)
- No operator overloading
- No variable argument lists or default arguments
- No pointer arithmetic
- All objects created with new, except
boolean, byte, char, short, int, long, float, double
- char is 16 bits, int is 32, long is 64
- No struct, union, enum, typedef, bitfields
- No delete (garbage collection)
- No templates
- No namespaces (use packages)
- Object is superclass of all classes
- No multiple inheritance except interfaces
Language features
- Literals - numbers, characters, Strings, boolean
- Types - primitive (int, char,...), array, String, Object
- Storage classes - local, instance, class (static)
- Operators - arithmetic, comparison, logical, assignment, conversion,
bitwise
- Statements - {block}, if, for, while, return, switch,
labelled break, continue, synchronized, try
- Classes - abstract, interface, final
- Methods - instance, static, constructors, finalize
- Access - package, public, private, protected
- Threads - start, run, synchronized, wait, sleep, interrupt
Standard packages
Java 1.0
- java.lang - Object, Integer (and other wrappers), Math, String,
System, Throwable, Thread
- java.util - Bitset, Date, Hashtable, Properties, Vector
- java.io - InputStream, BufferedInputStream, FileInputStream,
OutputStream, BufferedOutputStream, FileOutputStream, PrintStream, File
- java.net - URL, Socket, ServerSocket
- java.awt
- Component - Button, Canvas, Checkbox, Choice, Label, List,
Scrollbar, TextArea, TextField
- Container - Window, Frame, Dialog, FileDialog, Panel, (Applet)
- MenuComponent - MenuBar, MenuItem, Menu, CheckboxMenuItem
- LayoutManager - BorderLayout, FlowLayout, GridLayout, CardLayout,
GridBagLayout
- Graphics, Color, Dimension, Font, Image, Point, Polygon, Rectangle,
MediaTracker
- Event
- java.applet - Applet, AudioClip
- java.awt.image - not used
- java.awt.peer - not used
Java 1.1
- java.io - added for unicode character streams:
Reader, BufferedReader,
InputStreamReader, FileReader, Writer, BufferedWriter,
OutputStreamWriter, PrintWriter, FileWriter
- java.awt - added EventObject, ScrollPane
- java.awt.datatransfer - drag and drop applications
- java.beans - application builders
- java.lang.reflect - obtaining class data
- java.math - arbitrary range integers and reals
- java.rmi - remote method invocation, subpackages
java.rmi.registry, java.rmi.server
- java.security - encryption, signatures (no default
implementation), subpackages java.security.interfaces, java.security.acl
- java.sql - JDBC Java Database Connectivity
- java.text - Locale, NumberFormat, Calendar
(internationalization)
- java.util.zip - data compression
Java 2
- java.awt.dnd - drag and drop, also subpackages font,
geom, im, image.renderable, print
- java.lang.ref - reference object classes
- java.security -- added subpackages spec, cert
- java.util.jar - JAR files
- javax.accessability - magnifier, mousekeys
- javax.swing - new GUI subpackages border, choosecolor, event,
filechooser, plaf (pluggable look and feel), table, text, text.html,
text.rtf, tree, undo
- org.omg.CORBA - for talking to an Object Request Brokers (ORB).
Subpackages DynAnyPackage, ORBPackage, portable, TypeCodePackage,
and packages org.omg.CosNaming org.omg.CosNaming.NamingContextPackage
Compiling and Running Standalone Applications
Create a text file with a .java extension
edit Hello.java
Import packages as needed.
import java.io.*; // to read/write files
import java.net.*; // to send/receive over network
import java.util.*; // data structures (vector, hashtable) or dates
import java.awt.*; // if using a graphical user interface
Create a public class with the same name as your source code file.
public class Hello {
Add a method main exactly as follows, where your program will start.
public static void main(String[] args) {
Add your code.
System.out.println("Hello world");
} // end of main
} // end of MyProgram
The completed program looks like this.
Compile your program in a shell window or MS-DOS box
(produces Hello.class).
javac Hello.java
Run your program
java Hello
Hello world
Compiling and Running Applets
Create a text file with a .java extension (as before)
edit HelloApplet.java
Import the following at a minimum.
import java.applet.*;
import java.awt.*;
Extend the class Applet, matching your source code file name.
public class HelloApplet extends Applet {
Do not write main(). Override init(). This
will be the first method called when the applet starts up.
public void init() {
setBackground(Color.white);
setFont(new Font("Serif", Font.BOLD, 24));
}
Override paint(). This will be called whenever the applet
needs to be redrawn (such as when starting up or uncovered by a window).
public void paint(Graphics g) {
g.drawString("Hello World", 50, 100);
}
}
You will rarely need to override start(), stop(), or
destroy(). The
finished code will look like this.
To compile (as before).
javac HelloApplet.java
Create an HTML file with an APPLET tag. The tag should specify the
image size (in pixels), .class file name, and codebase (if not in the
current directory).
<APPLET WIDTH=300 HEIGHT=200 CODE="HelloApplet.class"></APPLET>
Test using appletviewer on the HTML file.
appletviewer HelloApplet.html
Place the HTML and .class file in the same directory on your web server.
Graphical User Interfaces
A GUI program or applet consists of two parts:
- Initialization (init() or main())
- Select a layout manager (FlowLayout, BorderLayout, GridLayout).
- Add components (Button, Checkbox, Choice, Label, TextField, TextArea,
Canvas, Panel).
- Repeat 1 and 2 for each Panel to form a hierarchical layout
- Add event handlers
- Java 1.0 override mousedown(), action(), keypress(), ...
- Java 1.1+ add event listeners.
Examples
- Scribble Applet demonstrates graphical
user interfaces (GUI) and the old Java 1.0 event model. Requires
Netscape 3.0 or IE 3.0.
- Scribble2 Applet using the
newer Java 1.1 event handling model. Requires Netscape 4.0 or IE 4.0.
Standalone programs
- Extend class Frame (a standalone window)
- Add layout managers, components, event handlers, etc.
- Call resize(x,y), pack() and show() to make
window visible.
- Add an event handler for window closing.
Call dispose() to close window before exiting.
Scribble3.java is like Scribble2,
modified to run as a standalone program.
Object Oriented Programming
- Construct a model.
- Classes are nouns - String, Component, Window, etc.
- Methods are verbs - compareTo(), setSize(), show(), etc.
- Use inheritance (extends or implements) to represent
is a - A Container is a Component. A Window is a
Container (general to specific).
- Use instance variables to represent has a. A Container
has a Button. A Button has a label (whole - parts).
- Use abstraction - public methods and private
instance variables (use public get and set methods to
access).
- If more than one implementation is possible, define an interface
- InputStream, Runnable, MouseListener.
- Use static members when you need global functions or constants - Math.
- Define a default constructor
- Pass constuctor arguments to superclass or another constructor.
- finalize() should call super.finalize()
interface Drawable {
public void draw();
}
class Shape implements Drawable {
private int x, y;
public Shape(int x, int y) {
this.x=x;
this.y=y;
}
public Shape() {
this(0, 0);
}
public int getX() {return x;}
public int getY() {return y;}
public static Shape makeShape(int x, int y) {
return new Shape(x, y);
}
public void draw() { /* overrides Drawable.draw() */ }
}
class Circle extends Shape {
private int radius;
public Circle(int x, int y, int r) {
super(x, y);
radius=r;
}
public Circle() {
this(0, 0, 0);
}
public int getRadius() {return radius;}
public void draw() { /* overrides Shape.draw() */ }
}
public class MyProgram {
public static void main(String[] args) {
Drawable d=Shape.makeShape(1, 2);
d.draw(); // draw a shape
d=new Circle(1, 2, 3);
d.draw(); // draw a circle
}
}
Threads
- Threads are active objects.
- Use a separate thread for each process that must wait on
something (input, CPU, client request, timeout).
- If an object is to be accessed by more than one thread, then
all methods that change its state should be synchronized.
- To create a thread, implement Runnable and override
run().
- To start a thread, call start() on it.
- To stop, return from run().
- sleep(ms) only when synchronized and catch
InterruptedException
- A program finishes when all threads finish.