6. JAVA Programming

• Basically a compact, object oriented language that is compiled to a machine independent form. This is then translated before execution for specific machines. The language has similarities to C/C++, and has embedded graphics and networking functions.

• This language uses the concept of a virtual machine to compile code. This provides some consistency when translating from the machine independent code into locally executable programs. This makes the code machine independent, and it also allows various protection mechanisms for the local machine, such as virus corruption, and read/write protection of local files.

• Java was originally conceived as a language for embedded controllers (and in a way still is). But more recently it has been adapted to the World Wide Web allowing an interactive extension to the normally reactive HTML.

• When used with HTML, Java programs are referred to as applets. These applets are binary coded (in a machine language for the virtual machine) and are translated to local machine language after downloading. The applets also checked for corruption using code check values, and checked for any operations that might be illegal locally.

6.1 The Language

• The programs are constructed out of objects: in a simplistic explanation each object is like a small subroutine, the main difference is that the object structure defines a hierarchy of functions, and allows functions to share and hide data and other functions in creative ways.

• Variables in Java are scoped to their declaration, and are static, but objects can be referred to dynamically.

• The Java source is compiled into ‘byte codes’, or a generic machine language, and then stored in ‘.class’ files. The byte codes are then translated into local machine code, with local extras added in.

• The Java applets are architecture neutral, and can be recompiled to other architectures. Machine specific details are considered using libraries. (using the prefix ‘java.’) An author may include none, some, or all the libraries in their programs. Although not consistent with the objectives of the language, customized libraries can also be added for special functions.

• Java uses “threads” to allow a program to split into parallel streams of execution. On a simple machine this won’t speed up execution, but will simplify programming.

• In Java there are no pointers, as a result the memory can be rearranged at times (stored variables and arrays can be moved in memory to be more compact. This “garbage collection” process is done automatically.

• Local code written in other languages can be used with the ‘native’ command.

• A simple example of an applet embedded in an HTML document is given (HTML is not the only way to run an applet)

<HTML><HEAD>

<TITLE=“A Java Applet”>

</HEAD>

<BODY>

<H1>Java Applet Below</H1>

<APPLET code=applet_name.class width=200 height=200>

<PARAM> name=file value=.cshrc>

<PARAM name=read_write value=read>

</APPLET>

</BODY></HTML>

• Applets can be organized using subdirectories, this is a good idea if there are many pieces. A good idea is have a subdirectory for each class/package. Under these have subdirectories for images, sounds, etc.

• Like most languages Java requires a compiler “javac” and then a separate viewer.

• Basic data types are,

boolean: a 1 bit true or false value

char: a 2 byte character

byte: a 1 byte integer

short: a 2 byte integer

int: a 4 byte integer

long: an 8 byte integer

float: a 4 byte floating point number

double: an 8 byte floating point number

• arrays (Note: No pointers) are defined as shown below, and have bounds checking when used.

int a[] = new int[10];

int[] a = new int[10];

int a[][] = new int[10][10];

int[][] a = new int[10][10];

int a[10] = {0,1,2,4,8,16,32,64,128,256};

int a[3][4] = {{0,1,2,4},{8,16,32,64},{128,256}};

• Basic syntax is like C/C++,

comments use ‘/*...*/’, or ‘//’

statements end in semicolons ‘;’

curly brackets start and end program blocks ‘{........}’

‘if’ statements use boolean arguments (but no others), for example,

if(A && B) is OK

if(A == 0) is OK

if(A = 0) is NOT OK

‘if...else’ statements are allowed

‘while’ and ‘do......while’ statements are allowed

‘for’ loops are used

‘switch’ statements are used

• classes are required for all code,

abstract: for a class that is not directly implemented

final: not allowed to be a subclass

public: the code can be used by other classes outside the package: the file. This class name must also be the name of the file <ClassName>.java

private: can only be used by code in the same file.

<empty>: if no access specifier is given (public or private), the class can be accessed from within the current package.

synchronizable: this function allows arguments that are instances of itself to allow synchronization.

• Functions in classes (Methods) can be modified using,

public: this function can be called by any other.

protected: this function can only be called by subclasses.

private: this function can only be called by peers in the same class.

<blank>: can be called by functions in the same package.

final: no other methods can be used to override.

static: a generally shared function by all subclasses started with <classname>.method_name.

synchronized: a lock will be applied and released on exit to prevent deadlock situations.

native: allows non-Java code to be used (e.g., a ‘C’ function)

• exceptions are one function not found in C/C++ and are intended to help trap errors. These exceptions are generated with ‘throw’ statements when a problem occurs. The results of a throw statement is then considered in another function by a ‘try...catch’ clock,

try{

// executed fully if no exception thrown

// If exception occurs run best match catch

} catch (exception e1){

//the best match for the exceptions will be found

} catch (exception e3){

} finally {

// do this wether or not there was an exception

}

• Recall, for class definitions, there is one function with the same name as the class (called the constructor) that is executed whenever a new instance of the class is created.

• functions may have the same name, but different arguments, this allows function overloading.

• the ‘this’ variable can be used to get a self reference to a function.

• There are no header files to include, but other classes or packages can be added using the ‘import’ function.

java.lang: the basic language classes (automatically imported)

java.io: allows input and output to other devices

java.util: utilities such as hash tables and vectors

java.net: network read/write functions

java.awt: GUI toolkit (e.g. windows)

java.applet: interfaces for WWW or other browsers

java.*: imports all

• ‘interface’ is a special command that allows inheritance without writing a new class. An interface can also be used to ‘extend’ a class.

• we can define classes that ‘implement’ one or more interfaces.

• Threads allow multiple streams of execution in parallel. Basically, if a program has to do more than one task, the traditional approach would be to do one for a while, then the other. But if at some point the program execution can be split (into threads) then execution will continue without paying attention to task switching. To do this a ‘Thread’ is initiated.

• If a class implements ‘Runnable’ it should have a function called run (needed for threads among other things).

• If running parallel threads, and they share common resources/data, we might take precautions to ensure that the two don’t read/write at the same time. We can do this by declaring potentially conflicting functions as ‘synchronized’. Care must be taken to avoid deadlock when a ‘synchronized’ function causes a monitor to lock a device/data needed by another ‘synchronized’ function. (these two or more functions would have to try to lock two or more resources).

6.2 Object Oriented Programming

• Inheritance allows us to write one generic class (function) that depends on other functions to deal with special cases (this can be done in other languages with function calls, but this is more consistent)

• an applet (note a special type of Java program) needs to have four functions,

init(): called when the applet is first loaded

start(): called when an applet becomes visible in the browser

stop(): called when the applet is no longer visible

destroy(): called when leaving a browser page

* init() is always called first, and then start() and stop() will be called while the document using the applet is alive. If the document is exited, then stop() will be called if not already, and destroy() will be called last before exiting.

• We can also call out to the parent HTML document. Generally, these calls deal with URL’s and parameters.

URL getDocumentBase(): returns the URL for the HTML document

URL getCodeBase(): returns the URL of the applet

String getParameter(String name): for the parameter with the ‘name’, the string value is returned

URL A = new URL(“http://www.computer.edu”);: define a URL

URL B = new URL(A, “directory/file.ext”);: define a new URL by extending the existing URL A

• Various types of media can also be included using simple functions.

Image getImage(URL): will set up a link to an image at a remote site to be used when the image is drawn.

Image getImage(URL, filename): an overloaded version that allows the filename string to be separated from the URL.

AudioClip getAudioClip(URL): will retrieve (but not play yet) an audio file. Functions available include,

play(): play the clip

loop(): play the clip continuously

stop(): stop playing the current clip.

AudioClip getAudioClip(URL, file_name)

void play(URL): plays an audio file directly

void play(URL, file_name)

• Applets can interact with the browser that has called it,

AppletContext getAppletContext(): gets a structure that is required by other functions.

Applet getApplet(String filename): retrieves an applet using an HTML parameter.

Enumeration getApplets(): returns applets on the current page.

void show Document(URL): allows a new document to be loadedin the browser.

void showStatus(String): the string is printed to the screen.

String get AppletInfo(): Can be used to return information about the applet.

String[][] getParameterInfo(): used to inform the browser what parameters are allowed.

• GUIs can be constructed using the ‘.awt’ toolkit. This allows the user to work with a variety of interface tools. The hierarchy is shown below.

GUI Components

Component: the basic class to represent the position & size of objects

Container: a class that can hold other classes

Panel: container in a container for organizing objects

Window: a rectangular area on the GUI

Frame: a window with a border added

Dialog: will receive input from the user

FileDialog: a file selection box

Button: when clicked on with a mouse will cause an action

Canvas: an area generally for free form I/O like lines and mouse events

Checkbox: will allow toggled or checked inputs

Label: a printed string

List: a scrolling list of strings

Scrollbar: can be attached to canvases to scroll

TextArea: a text editing window

TextField: a single text import line

• Components, and all objects in the hierarchy, can use the following functions.

Dimension Size(): returns width and height

Rectangle bounds(): return x, y, width, and height values

void enable(): sets a component to accept user input

void disable(): turns off user input to a component

void show(): makes a component visible

void paint(Graphics g): a function called to redraw a component

void repaint(): requests that a component be redrawn

void update(Graphics g): a level above a call to paint, might allow other function to be added

boolean mouseEnter(Event e, int x, int y): called when the mouse has entered a component

boolean mouseExit(Event e, intx, int y): called when the mouse leaves a component