Quick Java Reference
-
Getting Started
-
Local Information
-
Java Resources
-
AWT
-
Java Compiler
-
Packages
-
Command-Line Arguments
-
Applet Arguments
-
Timing
-
Java 2D API
-
Object References in Java
-
Inner Classes
-
Images in Java 2D
-
Random Numbers
-
Generic Programming
-
Bottom
Gettting Started
-
To call the compiler under jdk:
-
% javac [foo].java
This creates the file [foo].class.
-
In general, you can compile several files this way:
-
% javac foo1.java foo2.java ...
-
To run the program, do:
-
% java [foo] [runtime args]
where [foo].class is a compiled class with a "main" routine.
Local Java Information
If you are on the CS machines, then
the latest java compiler is found in /opt/java1.2/bin.
An older version is found in /opt/jdk1.1.5/bin.
Java Books and Resources
-
A compact intro in chap 2 of
-
"Concurrent Programming: THe java prog.lang"
by Stephen Hartley, Oxford University Press.
-
Another book from Oxford University Press by Bailey.
AWT
-
What is AWT (Abstract Windowing Toolkit)?
For an intro to AWT from
-
javaworld
Local copy: file
-
AWT has 9 non-container components:
-
Button, Canvas, Checkbox, Choice, Lable, List
Scrollbar, TextArea, TextField.
-
AWT has 4 container classes:
-
Window class: toplevel display surface (no border or title
and not embedded in other containers)
-
Frames class: subtype of window with border and title.
Can have menu bar.
-
Dialog class: subtype of window with border and title.
Cannot exist w/o an associated Frame class instance.
-
Panel class: generic container for holding components.
Applet class is a subclass of Panel class.
-
Java Tutorial
from Sun:
-
local copy
-
Applet Parameters:
-
http://java.sun.com/docs/books/tutorial/applet/appletsonly/param.html
-
Sample AppletButton code:
-
http://java.sun.com/docs/books/tutorial/ui/overview/example/AppletButton.java
-
AWT components, including an applet showing all the components:
-
http://java.sun.com/docs/books/tutorial/ui/overview/components.html
-
(a) Canvas
-
(b) text area
- >
(c) button
-
(d) choice item
-
(e) check box
-
(f) list items
-
Button demo:
-
http://java.sun.com/docs/books/tutorial/ui/components/example-1dot1/ButtonDemo.java
About the java compilers
Type:
% man javac
Packages
-
To import, e.g., put in preamble of program
-
import java.io.*
-
The packages in java.lang.* are automatically included,
so no need to import.
-
The packages included in java.lang include
-
System, Class, Integer, Math, String, Thread, etc
-
See /opt/jdk1.1.5/src/java/lang/
-
Other standard packages that you should know about are:
-
java.io
-
java.awt
-
java.beans
-
java.math -- has bigInteger!
-
java.applet
-
java.net
-
java.sql
-
Look in /opt/jdk1.1.5/src/java/{io,awt, etc.
Command-Line Arguments
Applet Arguments
- An applet can take arguments. Where are these arguments
specified? In the Html page that causes this applet to
be invoked:
<APPLET CODE=MyAppletSubclass.class WIDTH=anInt HEIGHT=anInt >
<PARAM NAME=param1Name VALUE=Value1 >
<PARAM NAME=param2Name VALUE=Value2 >
... html code for non-Java browsers ...
</APPLET >
-
The above example provides two arguments to
the applet MyAppletSubclass, namely
param1Name and param2Name.
The applet can receive the values (Value1
and Value2) for these parameters by invoking
the method getParameter which takes the parameter
name (which is a String) and returns a value (also a String):
String val1 = getParameter("param1Name");
As usual (See Command-line Arguments), if the val1
is a numeric value, you must convert it. E.g.
int v1 = Integer.parseInt(var1);
-
A more advanced topic is related to the method
getParameterInfo. See the
tutorial from Sun on this.
Timing
Use new Date().getTime() (found in java.util)
which returns a long unsigned integer
representing the current time in milliseconds.
To time any operation, you call this routine twice, once
at the start and once after the operation. The difference
is the timing in miliseconds.
If you need a finer time scale, you can call System.nanoTime()
instead. This will give you nanosecond accuracy.
Garbage collection shouldn't happen on small programs,
but we could test and if everytime the running time is the same.
If so, it is an 'accurate' way.
Further information: see my programs for Karatsuba's
algorithm and the Timing function there.
Java 2D API
- Java 2D
provides enhanced 2-D graphics and texts and imaging capabilities.
It is closely integrated with AWT, which you should
first review.
For more information, see
book from sun.
- Coordinate Systems.
Java 2D maintains 2 coordinate spaces: User space (where graphics
primitives are specified) and Device space (corresponding to the
output devicce such as screen, window or printer).
The origin of user space is the
upper-left corner of the component's drawing area.
- Rendering Model.
Java 2D API introduces java.awt.Graphics2D, a new type of
Graphics object. Graphics2D extends the Graphics class to
provide access to the enhanced graphics and rendering featuresI.
When a component is to be displayed, its paint() or update()
method is automatically invoked with an appropriate Graphics
context.
To use the Java 2D features, you cast a Graphics object
that is passed into a component's rendering method to a
Graphics2D object:
public void Paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
...
}
- Rendering Methods.
The following are provided:
- draw--renders the outline of any geometry primitive,
using the stroke and paint attributes.
- fill--renders any geometry primitive by filling its interior
with the color or pattern specified by the paint attribute.
- drawString--renders any text string. The font attribute is
used to convert the string to glyphs, which
are then filled with the color or pattern specified by the
paint attribute.
- drawImage--renders the specified image.
In addition, Graphics2D supports the Graphics rendering methods
for particular shapes, such as drawOval and fillRect.
- Rendering Context.
The collection of state attributes associated with a Graphics2D
object is referred to as the Graphics2D
rendering context. To display text, shapes, or images, you set up the
Graphics2D rendering context and then call the
above rendering methods, such as draw or fill.
Examples of attributes:
(1) pen style attribute determines how lines
are drawn.
(2) fill style determine how the interior of a shape is
filled in.
(3) compositing style attributes is used when rendered
objects overlap existing objects.
(4) transform attribute is used to convert the rendered
object from user space to device-space coordinates.
- Setting attributes:
To set an attribute in the Graphics2D rendering context,
you use the set Attribute methods:
setStroke setPaint setComposite setTransform setClip
setFont setRenderingHints
When you set an attribute, you pass in the appropriate attribute object.
For example, to change the paint attribute to a blue-green gradient
fill, you would construct a GradientPaint object and then call
setPaint.
gp = new GradientPaint(0f,0f,blue,0f,30f,green);
g2.setPaint(gp);
Graphics2D holds references to its attribute objects --
they are not cloned. If you alter an attribute object that
is part of the Graphics2D context, you need to call the
appropriate set method to notify the context.
Modifying an attribute object during rendering causes
unpredictable behavior.
Object References in Java
When we pass an object (e.g., Integer) as a parameter to a method,
the conventional description is that it is "passed by reference".
In contrast, when we pass a primitive (e.g., int), we say it
is "passed by value". Despite this conventional terminology,
it is often hotly debated (do websearch) whether Java objects are really passed
by reference or by value. This is a subtle programming
concept that we will not enter in much detail.
If you know about pointers, then the answer is this: whenever we pass an object
to a Java method, we are passing the value of the pointer
(not the pointer itself). In this sense, we are passing
the object parameter "by value" (but it is not "value" in the naive sense).
To illustrate these concepts, suppose we
write a simple wrapper class called MyInt, that is similar to Integer:
public class MyInt{
int val=0;
//constructor:
public MyInt(int k) { val = k; }
//access methods:
public void setVal(int n){ val=n; }
public int getVal(){ return val; }
//string method
public String toString(){ return Integer.toString(val);}
}
Consider the following attempt to assign to an object parameter inside a method.
we present two methods -- one method fails, the other succeeds.
public class RefDemo {
static public void setIntFail(int n, MyInt N){
System.out.println("n = " + n + ", N = " + N);
N = new MyInt(100);
}
static public void setIntSucc(int n, MyInt N){
System.out.println("n = " + n + ", N = " + N);
N.setVal(100);
}
public static void main(String[] args){
MyInt NN = new MyInt(0);
setIntFail(1,NN);
System.out.println("NN = " + NN + " (Failure: NN has not changed to 100)");
setIntSucc(2,NN);
System.out.println("NN = " + NN + " (Success: NN has changed to 100)");
}
}
Here is the output:
> javac MyInt.java RefDemo.java
> java RefDemo
n = 1, N = 0
NN = 0 (Failure: NN has not changed to 100)
n = 2, N = 0
NN = 100 (Success: NN has changed to 100)
NOTE: we couldn't use Integer for our demo becasue Integer class is "final".
Inner Classes
Inner classes are those classes that are defined
within the scope of another (outer) class.
There are two varieties: static and non-static.
In the following example, the class Outer has
two inner classes, one static and one non-static:
public class Outer {
static int s;
int n;
public static class InnerStatic {
int m;
void f(){
System.out.println("s = " + s); // This is OK
m = n; // ERROR! Cannot access
// non-static member of outer class.
}
}
public class InnerNonStatic {
int m;
void f(){
System.out.println("s = " + s); // This is OK
m = n; // This is OK too
}
}
}
From InnerNonStatic, you can refer to your own instance by the
usual \verb+this+, but you can also refer to the outer
instance using \verb+Outer.this+. Both of these
references do not make sense for InnerStatic.
Why Inner Classes? This is one way to organize your programs
so that you can conveniently refer to certain methods/fields
without much fuss (and without making these methods/fields public).
This is used frequently in Java2D, e.g.,
in the the Point2D class.
Images in Java 2D
We treat images separately than the rest of the Java 2D.
For more information, see
tutorial from Sun.
-
Java 2D implements a new imaging model that supports the
manipulation of fixed-resolution images stored in memory.
A new Image class in the java.awt.image package,
BufferedImage,
can be used to hold and to manipulate image data
retrieved from a file or a URL. For example, a BufferedImage can be
used to implement double buffering--the graphic elements are
rendered off-screen to the BufferedImage
and are then copied to the screen through a call to Graphics2D
drawImage. The classes BufferedImage
and BufferedImageOp also enable you to perform a variety of
image-filtering operations, such as blur and
sharpen. The producer/consumer imaging model provided in
previous versions of the JDK is supported for backward compatibility.
Random Numbers
To access random numbers, you need to include a package:
import java.util.Random; // or: import java.util.*;
Next, you need to set up the random number generator:
Random generator = new Random(1000); // 1000 is the seed.
You may omit the seed, which is an optional argument.
Now, we can use the random number generator to generate
random int values, using one of the following calls:
int randInt = generator.nextInt();
int randInt = generator.nextInt(100); // generate value between 0--99.
We can similarly generate random float values:
double randflot = generator.nextDouble(); // generate uniform value between 0 and 1.0
double randflot = generator.nextGaussian(); // generate Gaussian distributed value between 0 and 1.0
Note that nextDouble()
and
nextGaussian()
do not take any arguments.
Generic Programming
Java 1.5 introduced generic programming into the language.
Recall the "List" interface in java.
We would like to talk about a List of Integers, a List of Strings, etc.
In general, we wish to have a List of E, where E is any (non-primitive) type.
We can therefore define a class called "List<E>" where E is a type variable,
to be instantiated when we actually use the class.
E can be instantiated by Interfaces or Classes,
but not primitive types (like int). Call "List<E>" a generic class.
We will discuss the three generic programming mechanisms:
(a) generic interfaces (e.g., java.util.List),
(b) generic classes (e.g., java.util.AbstractList),
and (c) generic methods.
[NOTE: in C++, the generic programming mechanism is called "templates" and
there are differences how the concept is implemented.]
- Generic classes or interfaces. You defined a generic class like
List<E> in the same way you define a non-generic class, except that
you can use "E" in the definition as a type.
E.g., here is an implementation of a generic queue:
import java.util.ArrayList;
public class MyQueue extends ArrayList {
public void push(E item) {add(item);}
public E pop() {remove(0);}
}
To use it, you can extend this generic class, or declare objects
by instantiating the generic type:
MyQueue qi = new MyQueue();
qi.push(3);
System.out.println("Pop = " + qi.pop());
Perhaps the most important mistake to avoid is that
if E and T are two distinct types, then MyQueue<T> and
MyQueue<E> are not related in any way by any subclass relationship.
(You might expect that if T is a subclass of E, then
MyQueue<T> should be a subclass of MyQueue<E>).
- Generic Methods.
What are they? It is a method that can accept unknown types.
Consider the following method to print
static <T> void printMyQueue(MyQueue<T> qq) {
for (T e: c){
System.out.println(e);
}
}
Another useful technique is the notion of wildcards:
You can define a method with "wildcard type":
void printMyQueue(myQueue<?> qq) {
for (Object e: c){
System.out.println(e);
}
}
An annoying quirk of Java is its treatment of generic arrays.
Apparently, there is no way to initialize a generic array
in a generic class! You might try:
class GenericClass {
T [] myArray = new T[100]; // illegal
T [] myArray = (T []) new Object [100]; // Cast from Object: compiler warning
T element(1);
myArray[0] = element;
}
The compiler warning can be suppressed.
In general, you cannot create instances of a generic type:
T myObj = new T(); // illegal, as T is a type variable
There is a lot of discussion of this issue, especially of
"generic array creation" in the web. The following nice solution
uses reflection, and is taken from
http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation:
import java.lang.reflect.Array;
public class GenericSet
{
private E[ ] a;
// WATCH THIS CONSTRUCTOR CLOSELY:
public GenericSet(Class clazz, int length)
{
a = clazz.cast(Array.newInstance(clazz.getComponentType( ), length));
}
public static void main(String[ ] args)
{
// SEE HOW WE INVOKE THE CONSTRUCTOR:
GenericSet foo = new GenericSet(String[ ].class, 1);
// Now, foo.a can be used freely, as expected:
String[ ] bar = foo.a;
foo.a[0] = "xyzzy";
String baz = foo.a[0];
}
}
Note that the GenericSet constructor requires a Class object called
clazz. This object is able to carry the type information (overcoming "type erasure")
of generic types. To use it (when calling the GenericSet constructor)
we need to follow the name of the class with a .class. Above, we use "String[ ].class".
This is an example of "class literals" from Java Tutorials,
which the compiler treats as instances of java.lang.Class.
Go to Top