Java:

The White Paper

The White Paper on Java uses the following eleven adjectives to describe the Java Language and Platform:

·  Simple

·  Object Oriented

·  Distributed

·  Robust

·  Secure

·  Architecture Neutral

·  Portable

·  Interpreted

·  High Performance

·  Multithreaded

·  Dynamic

·  Simple

o  Streamlined C++

§  No Header Files

§  No Pointer Arithmetic

§  No Structures, Unions, Operator Overloading, Virtual Base Classes, etc.

o  Small

§  Only 250K for the interpreter and base libraries

·  Distributed

o  import v. #include

o  networking

·  Robust

o  Java pointers

o  extensive error checking at both compile and run time

·  Secure

o  Java pointers

o  Class Loader

§  Byte Verifier

o  Security Manager

§  Applications v. Applets

·  Architecture Neutral

o  Byte Code is Byte Code

·  Portable

o  Fixed sizes primitive data types

§  32-bit Integers

§  Unicode

o  AWT to Swing

·  Interpreted

o  Faster than data stream

§  C++ simply waits longer

§  Recent optimized compilers get close to C++

o  JIT Compilers x10-x20

·  Multithreaded

o  Multiprocessing at the sub-process level

§  better interactive responsiveness and real time behavior

o  Extremely useful on Server side

·  Dynamic

o  Class Loader

§  Virtually All Objects Dynamically Allocated

§  . . . and Garbage Collected

o  Reflection and Introspection

·  JDK1.0.2

·  JDK1.1

o  JDK1.1.1

o  . . .

o  JDK1.1.8

·  JDK1.2 - Platform 2

o  http://java.sun.com/

§  add "C:\jdk1.x\bin" to path

Compiling and Running the Hello World Application

class HelloWorldApp {

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

o  save as text file HelloWorldApp.java

o  at command line type>javac HelloWorldApp.java

o  execute program by typing>java HelloWorldApp

Compiling and Running the Hello World Applet

import java.applet.Applet;import java.awt.Graphics;class HelloWorldApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello World!", 50, 25);

}

}

o  save as text file HelloWorldApplet.java

o  at command line type>javac HelloWorldApplet.java

o  execution is performed by viewer (browser)

Methods to override:

·  init();

·  start();

·  stop();

·  destroy();

·  paint();

Simple HTML

·  Texts:

o  Core Java by Horstmann and Cornell (Sun and Prentice Hall)

o  The Java Tutorial by Campione and Walrath (Sun and Prentice Hall)

·  Online:

o  The Java Tutorial - http://java.sun.com/tutorial

o  JavaWorld Magazine - http://www.javaworld.com

o  Gamelan - http://www.gamelan.com

o  Excite, AltaVista, WebCrawler, etc.

o  A Beginner's Guide to HTML (NSCA)

Lecture 1b

Differences between C++ and Java

C++ is a superset of C while Java is a strictly Object Oriented Language.

·  C is procedural while C++ is object oriented

o  Many C++ programmers write non-OO code

o  Can't get away with that in Java

o  In Java, all classes descend from "Object"

·  C++ allows multiple inheritance while Java uses Interfaces.

o  Object Communication

o  An interface is a protocol by which two otherwise unrelated objects communicate

·  C++ runs on the hardware machine while Java runs on a Virtual machine.

o  Java Virtual Machine - Java Runtime Environment

·  C++ makes extensive use of pointers while Java has no specific pointer type.

·  In addition to the access specifiers of C++ (public, protected & private), Java adds a new one (package).

o  Individually tagged

·  C++ allows operator overloading; Java does not.

·  Java allows inner classes and anonymous inner classes; C++ does not.

·  Java is Garbage Collected; C++ is not.

o  new

o  no delete

·  In Java, arrays are objects.

o  out of bounds

o  length

class HelloWorldApp {

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

// Not a GUI program.

GUI

For even the most basic GUI, one needs a working knowledge of :

o  Layout Managers

o  Interfaces

o  AWT (or Swing) widgets

§  1.1 Event Handling

import java.awt.*;import java.awt.event.*;public class CloseableFrame extends Frame{

public CloseableFrame(){ addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0); } } );

setSize(300, 200);setTitle(getClass().getName());}

}

Resources

·  Texts:

o  Core Java by Horstmann and Cornell (Sun and Prentice Hall)

o  The Java Tutorial by Campione and Walrath (Sun and Prentice Hall)

·  Online:

o  The Java Tutorial - http://java.sun.com/tutorial

o  JavaWorld Magazine - http://www.javaworld.com

o  Gamelan - http://www.gamelan.com

o  Excite, AltaVista, WebCrawler, etc.

Lecture #2

Reserved Words

abstract do implements private throws

boolean double import protected transient

break else inner public true

byte extends instanceof rest try

byvalue false int return var

case final interface short void

cast finally long static volatile

catch float native strictfp while

char for new super widefp

class future null switch

const generic operator synchronized

continue goto outer this

default if package throw

Reserved Words (Not Currently Used)

byvalue future inner rest

cast generic operator var

const goto outer

Non-Reserved Words (Examples)

delete include

define inline

friend using

ifdef virtual

Identifiers

o  Theoretically may be made up from the Unicode character set but the tools only work with ASCII.

o  The first character may only be a letter, a dollar sign or and underscore.

MyVariable $anotherName _yetAnotherName

o  However, the convention is that method names start with a lower case letter:

public void myMethodThatDoesAmazingThings(){}

o  While Variables and Class names start with an upper case letter:

public class MyClass {

public int MyVariable = 5;

}

Primitives

Type Contains Size Range

byte signed integer 8 bits -128 to 127

short signed integer 16 bits -32768 to 32767

char unsigned Unicode 16 bits \u0000 to \u FFFF

int signed integer 32 bits -231 to 231 – 1

float single precision 32 bits 1.4 x 10-45 to 3.4 x 1038

double double precision 64 bits 4.9 x 10-324 to 1.8 x 10308

boolean true or false ------true or false

Primitives v. Reference Variables (Object Wrappers)

Primitive Object

byte Byte

short Short

char Char

int Integer

float Float

double Double

boolean Boolean


public class SimplePoint {

public int x = 0;

public int y = 0;

}

public class SimpleRectangle {

public int width = 0;

public int height = 0;

public SimplePoint origin = new SimplePoint();

}

public class Point {

public int x = 0;

public int y = 0;

// a constructor!

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

Passing Arguments

o  In Java variables are passed by value.

The Class Declaration

o  public

§  By default, a class can be used only by other classes in the same package. The public modifier declares that the class can be used by any class regardless of its package.

o  abstract

§  Declares that the class cannot be instantiated.

o  final

§  Declares that the class cannot be subclasssed.

o  class NameOfClass

§  The class keyword indicates to the compiler that this is a class declaration and that the name of the class is NameOfClass.

o  extends Super

§  The extends clause identifies Super as the superclass of the class, thereby inserting the class within the class hierarchy.

o  implements Interfaces

§  To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the names of the interfaces implemented by the class.

public final class MyClass extends Applet implements ItemListener, ActionListener {

. . .

}

Access Specifiers

o  private

§  Only accessible from within the class (not merely the instance).

o  protected

§  Also accessible from subclasses and package members.

o  package

§  Accessible from package members. (Friends, not family)

o  public

o  No restrictions. Accessible from anywhere.


Providing Constructors for Your Classes

Constructor Defined:

Default

public Stack() {

items = new Vector(10);

}

Overloaded

public Stack(int initialSize) {

items = new Vector(initialSize);

}

Constructor Called:

stack MyStack = new Stack(10);

stack MyOtherStack = new Stack();

This and Super

class AnimationThread extends Thread {

int framesPerSecond;

int numImages;

Image[] images;

AnimationThread(int fps, int num) {

super("AnimationThread");

this.framesPerSecond = fps;

this.numImages = num;

this.images = new Image[numImages];

for (int i = 0; i <= numImages; i++) {

. . .

// Load all the images.

. . .

}

}

. . .

}

public class Rectangle {

public int width = 0;

public int height = 0;

public Point origin;

// four constructors

public Rectangle() {

origin = new Point(0, 0);

}

public Rectangle(Point p) {

origin = p;

}

public Rectangle(int w, int h) {

this(new Point(0, 0), w, h);

}

public Rectangle(Point p, int w, int h) {

origin = p;

width = w;

height = h;

}

// a method for moving the rectangle

public void move(int x, int y) {

origin.x = x;

origin.y = y;

}

// a method for computing the area of the rectangle

public int area() {

return width * height;

}

// clean up!

protected void finalize() throws Throwable {

origin = null;

super.finalize();

}

}

Declaring Member Variables

Access Level

Public, protected, package, and private.

static

Declares this is a class variable rather than an instance variable. You also use static to declare class methods.

final

Indicates that the value of this member cannot change.

transient

Used in serialization to mark variables that should not be serialized.

volatile

The volatile keyword is used to prevent the compiler from performing certain optimizations on a member.

type

Like other variables, a member variable must have a type. You can use primitive type names such as int, float, or boolean. Or you can use reference types, such as array, object, or interface names.

name

A member variable's name can be any legal Java identifier. You cannot declare more than one member variable with the same name in the same class, but a subclass can hide a member variable of the same name in its superclass.

Additionally, a member variable and a method can have the same name. For example, the following code is legal:

public class Stack {

private Vector items;

// a method with same name as a member variable

public Vector items() {

. . .

}}

Variable Examples

public int MyInt = 5;

public final int AnotherInt = 10;

private final long YetAnother = 76L;

float MyDecimal = 30.0;

Point myPoint = new Point();

final Point MyOtherPoint = new Point(5,7);

Details of a Method Declaration

Access Level

Public, protected, package, and private

static

As with member variables, static declares this method as a class method rather than an instance method.

abstract

An abstract method has no implementation and must be a member of an abstract class.

final

A final method cannot be overridden by subclasses.

native

Methods implemented in a language other than Java are called native methods and are declared as such using the native keyword.

synchronized

Concurrently running threads often invoke methods that operate on the same data. These methods may be declared synchronized to ensure that the threads access information in a thread-safe manner.

returnType

If your method does not return a value, use the keyword void for the return type.

methodName

( paramlist )

You pass information into a method through its arguments

[throws exceptions]

If your method throws any checked exceptions, your method declaration must indicate the type of those exceptions

Returning a Value from a Method

public boolean isEmpty() {

if (items.size() == 0)

return true;

else return false;

}

Returns a primitive.

public synchronized Object pop() {

int len = items.size();

Object obj = null;

if (len == 0)

throw new EmptyStackException();

obj = items.elementAt(len - 1);

items.removeElementAt(len - 1);

return obj;

}

Returns an object.

Remember: When a method returns an object such as pop does, the class of the returned object must be either a subclass of or the exact class of the return type.

This Revisited

class HSBColor {

int hue, saturation, brightness;

HSBColor (int hue, int saturation, int brightness) {

this.hue = hue;

this.saturation = saturation;

this.brightness = brightness;

}

. . .

}


Super Revisited

A class:

class ASillyClass {

boolean aVariable;

void aMethod() {

aVariable = true;

}

}

and its subclass which hides aVariable and overrides aMethod;

class ASillierClass extends ASillyClass {

boolean aVariable;

void aMethod() {

aVariable = false;

super.aMethod();

System.out.println(aVariable);

System.out.println(super.aVariable);

}

}

overriden method invoked with this statement:

super.aMethod();

aMethod displays both versions of aVariable which have different values:

false

true

Access Specification

Private Access:

class Alpha {

private int iamprivate;

boolean isEqualTo(Alpha anotherAlpha) {

if (this.iamprivate == anotherAlpha.iamprivate)

return true;

else

return false;

}

}

Package Access:

package Greek;

class Alpha {

int iampackage;

void packageMethod() {

System.out.println("packageMethod");

}

}

package Greek;

class Beta {

void accessMethod() {

Alpha a = new Alpha();

a.iampackage = 10; // legal

a.packageMethod(); // legal

}

}

Protected Access: (Caveat)

package Greek;

class Alpha {

protected int iamprotected;

protected void protectedMethod() {

System.out.println("protectedMethod");

}

}

package Greek;

class Gamma {

void accessMethod() {

Alpha a = new Alpha();

a.iamprotected = 10; // legal

a.protectedMethod(); // legal

}

}

package Latin;

import Greek.*;

class Delta extends Alpha { //class Alpha must be public

void accessMethod(Alpha a, Delta d) {

a.iamprotected = 10; // illegal

d.iamprotected = 10; // legal

a.protectedMethod(); // illegal

d.protectedMethod(); // legal

}

}

Instance Members v. Class Members

class AnIntegerNamedX {

int x;

public int x() {

return x;

}

public void setX(int newX) {

x = newX;

}

}