You are on page 1of 134

Table of Contents Last printed 2/3/2004 10:24:00 AM

TYPING IN A JAVA PROGRAM......................................................................................................................................1

BYTECODES........................................................................................................................................................................1

JAVA VIRTUAL MACHINE.............................................................................................................................................2


CREATING A JAVA SOURCE PROGRAM..................................................................................................................................2
INTRODUCTORY EXERCISE 1 - PAINT() AND MORE!.......................................................................................3
INTRODUCES:......................................................................................................................................................................3
Getting Help in Java.......................................................................................................................................................3
Packages.........................................................................................................................................................................4
Class...............................................................................................................................................................................4
Paint( )............................................................................................................................................................................4
Fonts...............................................................................................................................................................................4
Colors.............................................................................................................................................................................4
Window Coordinates......................................................................................................................................................5
Strings.............................................................................................................................................................................5
Graphics Objects............................................................................................................................................................5
Practical Exercise 1.......................................................................................................................................................6
INTRODUCTORY EXERCISE 2 -INTEGER VARIABLES.....................................................................................8
Variables........................................................................................................................................................................8
Basic integer operations.................................................................................................................................................9
The init() method............................................................................................................................................................9
Theoretical Exercise 2..................................................................................................................................................10
INTRODUCTORY EXERCISES 3 - OBJECTS.........................................................................................................11
Objects..........................................................................................................................................................................11
Global declaration of the objects.................................................................................................................................12
Practical Exercise 3.....................................................................................................................................................12
INTRODUCTORY EXERCISE 4 -STRINGS............................................................................................................13
Strings...........................................................................................................................................................................14
String methods..............................................................................................................................................................14
PRACTICAL EXERCISE 4..............................................................................................................................................14

INTRODUCTORY EXERCISE 5 - COMPONENTS................................................................................................15


Components..................................................................................................................................................................15
Controlling the layout of the window...........................................................................................................................16
Practical Exercise 5.....................................................................................................................................................16
INTRODUCTORY EXERCISE 6 - EVENTS............................................................................................................17
Events...........................................................................................................................................................................18
Converting integers to strings and strings to integers.................................................................................................18
Practical Exercise 6.....................................................................................................................................................19
Theoretical Exercise 6..................................................................................................................................................19
INTRODUCTORY EXERCISE 7 -IMAGES.............................................................................................................20
Getting an image..........................................................................................................................................................20
Painting an image........................................................................................................................................................21
Practical Exercise 7.....................................................................................................................................................21
INTRODUCTORY EXERCISE 8 -SOUND...............................................................................................................22
Practical Exercise 8a...................................................................................................................................................22
Practical Exercise 8b...................................................................................................................................................23
INTRODUCTORY EXERCISE 9 -MORE ON NUMBERS AND STRINGS.........................................................24
Revision........................................................................................................................................................................24
Converting between strings and doubles......................................................................................................................25

Java Page - 1
Table of Contents Last printed 2/3/2004 10:24:00 AM
PRACTICAL EXERCISES 9............................................................................................................................................25

TYPE IN, AND GET THE ABOVE CLASS GOING.INTRODUCTORY EXERCISE 10 - REAL NUMBERS
(AND MORE!) 25

INTRODUCTORY EXERCISE 10 - REAL NUMBERS (AND MORE!)................................................................26


Number Types...............................................................................................................................................................27
Precedence of Mathematical Operations.....................................................................................................................27
Mathematics Methods...................................................................................................................................................27
Math.sqrt(double) square root................................................................................................................................27
Promoting.....................................................................................................................................................................27
Casting..........................................................................................................................................................................27
Theoretical Exercise 10................................................................................................................................................28
Practical Exercises 10..................................................................................................................................................28
INTRODUCTORY EXERCISE 11 - THE IF STATEMENT....................................................................................28
Equality and Relational Operators..............................................................................................................................29
The if statement............................................................................................................................................................29
Practical Exercises 11..................................................................................................................................................29
11.4 Getting numbers in order (Sample solution Ex 11_4_Order)..........................................................................30
INTRODUCTORY EXERCISE 12 - IF ELSE STATEMENTS................................................................................31
Why use if .. else statements.........................................................................................................................................32
Programming exercises 12...........................................................................................................................................32
INTRODUCTORY EXERCISE 13 THE FOR LOOP...............................................................................................33
The for loop..................................................................................................................................................................33
Programming exercises 13...........................................................................................................................................34
EXERCISE 14 VARIABLES IN JAVA....................................................................................................................35
Variable types...............................................................................................................................................................35
Basic integer operations (types int and long)..............................................................................................................36
Basic real operations (types float and double)............................................................................................................36
Precedence of Mathematical Operations (all types)....................................................................................................36
Promoting.....................................................................................................................................................................36
Casting..........................................................................................................................................................................37
Mathematics Methods...................................................................................................................................................37
Writing the integer values to the applet window..........................................................................................................37
Controlling the number of decimal places in a printout..............................................................................................37
Converting text (in a TextField) to numbers................................................................................................................38
The boolean type..........................................................................................................................................................38
Order of precedence including comparison operators................................................................................................39
The character type char...............................................................................................................................................39
Operations on characters.............................................................................................................................................39
Characters and strings.................................................................................................................................................39
Character methods.......................................................................................................................................................40
Theoretical Exercise 14................................................................................................................................................41
EXERCISE 15 METHODS........................................................................................................................................42
The standard Applet methods.......................................................................................................................................42
More on paint()............................................................................................................................................................42
repaint()........................................................................................................................................................................42
What do you code in paint() and in the various event methods?.................................................................................43
EXERCISE 16 WRITING YOUR OWN METHODS............................................................................................44
Methods with no input or output..................................................................................................................................44
Method with an input or parameter but no output to the class....................................................................................44
Method with input parameter and output to an object in the class..............................................................................45
Method with input parameter and output which changes the input value...................................................................45
Method which has no input but generates or “returns” a new value..........................................................................46
Method which has an input and generates a new value...............................................................................................47

Java Page - 2
Table of Contents Last printed 2/3/2004 10:24:00 AM
A summary of the theory of methods in Java................................................................................................................48
The method call............................................................................................................................................................48
Formal and Actual parameters....................................................................................................................................50
Call-By-Value and Call-By-Reference.........................................................................................................................50
Method Overloading.....................................................................................................................................................51
Modularising Graphics................................................................................................................................................52
More advanced topics, including notes on using the JWS API help:...........................................................................53
Public private and protected methods..........................................................................................................................53
Instance and Static methods.........................................................................................................................................53
Instance and Static variables.......................................................................................................................................53
Wrapping......................................................................................................................................................................54
Methods and Constructors...........................................................................................................................................54
Classes and Interfaces:................................................................................................................................................54
Programming exercises 16...........................................................................................................................................55
Introductory exercises in Methods...............................................................................................................................57
EXERCISE 17 MOUSE EVENTS AND EVENTS DUE TO OTHER COMPONENTS EVENTS...........................60
The ActionListener interface........................................................................................................................................60
How do you decide which component generated an event?.........................................................................................60
Other interfaces............................................................................................................................................................60
Some other components that generate Events..............................................................................................................61
Checkboxes (use ItemListener interface).....................................................................................................................62
Scroll bars (uses AdjustmentListener interface)..........................................................................................................64
Keyboard events (including the KeyListener interface)...............................................................................................65
Mouse events: MouseListener interface.......................................................................................................................66
Mouse events: MouseMotionListener interface...........................................................................................................67
Using the mouse to draw on the screen........................................................................................................................68
Practical exercises.......................................................................................................................................................70
EXERCISE 18 JAVA NOTES: CONTROL STRUCTURES.................................................................................71
Conditional statements.................................................................................................................................................71
If statement:..................................................................................................................................................................71
Compound if statement.................................................................................................................................................71
Nested if statements......................................................................................................................................................71
if .. else statements........................................................................................................................................................71
The “dangling” else.....................................................................................................................................................72
Switch statements.........................................................................................................................................................72
Programming exercises 18...........................................................................................................................................73
Theoretical exercises 18...............................................................................................................................................74
Break and continue.......................................................................................................................................................78
While and do loops.......................................................................................................................................................78
“break” and “continue” in while and do loops...........................................................................................................79
Theoretical exercises....................................................................................................................................................79
More Programming exercises......................................................................................................................................80
EXERCISE 19 CLASSES AND OBJECTS..............................................................................................................83
What are objects and classes?......................................................................................................................................83
Instantiating an object..................................................................................................................................................83
What are principles of object-oriented programming (OOP)?....................................................................................83
Inheritance....................................................................................................................................................................87
Exercises 19..................................................................................................................................................................89
Objects & Classes- exercises.......................................................................................................................................91
Initialization and construction.....................................................................................................................................91
Summary: GUI objects.................................................................................................................................................93
Sample questions from mid year papers.......................................................................................................................97
EXERCISE 20 ARRAYS..........................................................................................................................................101
Array Processing Techniques.....................................................................................................................................102
Making A Copy Of An Array......................................................................................................................................103
Sorting An Array........................................................................................................................................................103
Two-Dimensional Arrays...........................................................................................................................................105
Arrays programming exercises 20.............................................................................................................................107

Java Page - 3
Table of Contents Last printed 2/3/2004 10:24:00 AM
Problems in Arrays 20................................................................................................................................................108
EXERCISE 21 CHARACTERS AND STRINGS..................................................................................................111
Strings.........................................................................................................................................................................111
Exercises 21................................................................................................................................................................114
EXERCISE 22 THREADS IN GAMES WITH ANIMATION.............................................................................115
Single Thread.............................................................................................................................................................115
Two Threads...............................................................................................................................................................115
Three Threads.............................................................................................................................................................115
Four Threads..............................................................................................................................................................115
Many Threads.............................................................................................................................................................115
A summary of the techniques used to control various numbers of Threads...............................................................116
Single Thread.............................................................................................................................................................116
Multiple Threads........................................................................................................................................................116
Runnable.....................................................................................................................................................................117
Declaring separate Classes to create the multiple Thread objects............................................................................117
Stopping a Thread......................................................................................................................................................118
EXERCISE 23 GRAPHICS IN GAMES WITH ANIMATION...........................................................................120
How do you draw to the screen?................................................................................................................................120
Double Buffering........................................................................................................................................................120
Update........................................................................................................................................................................120
Using file images........................................................................................................................................................121
Problems with starting the program..........................................................................................................................121
Flicker1......................................................................................................................................................................122
Flicker2......................................................................................................................................................................122
Flicker3......................................................................................................................................................................122
Exercise 24 Notes on games which make use of Thread techniques.................................................................123

Java Page - 4
A Word about the Java Platform
The Java platform consists of the Java application programming interfaces (APIs) and the Java
virtual machine (JVM).

Java APIs are libraries of compiled code that you can use in your programs.
They let you add ready-made and customizable functionality to save you
programming time.

Typing in a Java program


When you create your first Java program (following the instructions in Practical
Exercise 1), this program will be created as a text file, and the important thing for now is to note it is
a file that is saved on the hard disk. The file will be saved as PaintDemo.java. This file is
called a source program.
Since the file contains characters (stored as bytes) it cannot be directly executed (run)
by the computer system. As a file containing text, all that can be done with it is to print
it, display it on the monitor, or alter it with a text editor.

Another file is also saved at this time


Bytecodes
To get the sample program running, it first is translated into bytecodes.
A Java bytecode is a machine instruction for a Java processor chip. The architecture of
this processor has been very carefully described by the designers of Java and is freely
available to anyone.
To run a Java program on the Java processor chip, the souce program (the text file) must be
translated into bytecodes. (You will soon see that you do not actually need the Java processor chip
in your computer to run Java.) Here is a picture of the sample Java program Hello.java being
translated into bytecodes. The file of bytecodes (machine language for the Java chip) is called
Hello.class.

javac

Source Program Java compiler Java Bytecodes

Java Program Translation


In this picture, the source program PaintDemo.java is examined by a program called javac running
on your computer. The javac program is a compiler (a translator) that translates the source program
into a bytecode file called PaintDemo.class.
Important Idea: The bytecode file will contain exactly the same bytecodes no matter what computer
system is used.
The Java compiler on a Macintosh will produce the exact same bytecodes as the Java compiler on
an Intel system.
Java Virtual Machine
Now for the clever part: a Java bytecode interpreter executes the bytecode file. The Java bytecode
interpreter is an executable program for whatever processor you computer system has. Here is a
picture showing this:

The "Java interpreter" in the picture is an executable program that is running on the computer
system. Each type of computer system has its own Java interpreter that can run on that system. The
"Actual processor" is the actual, hardware, processor chip of that computer system.
(Another) Important Idea: The Java interpreter running on any computer system "looks like" the
hardware Java processor chip. It is a Java Virtual Machine.
Any computer system can execute all Java bytecode programs if it has a Java interpreter. The Java
interpreter has to be specifically written for the specific processor type of the computer system, but
once that is done, the computer system can become a Java virtual machine. That is, it looks like a
computer with a Java processor chip and can run Java bytecodes.
Remember that when a Java program is translated into bytecodes, the bytecodes are exactly the
same no matter what computer system is used. This means the bytecodes on a Sun computer can
be sent to an Intel based computer and they will run without a problem.
An applet is a Java bytecode program that runs on a Web browser. Most up-to-date Web browsers
include a Java interpreter. A Web page on a host computer on the Internet can contain instructions
that send Java bytecodes to a client computer (like yours) that has asked to view the page. The
Web browser on the client runs the Java applet with its built-in interpreter.

Creating a Java Source Program


When you run the applet, it saves the java project file
Introductory Exercise 1 - Paint() and more!
Introduces:
 The java applet and awt packages.
 The idea of a class.
 The paint() method.
 Using fonts
 Using colors
 Using basic graphics objects.

Getting Help in Java


Some useful online references include:

A Java tutorial which takes you through the basics of programming in Java.
http://www.javasoft.com/docs/books/tutorial/java/index.html

The Java API help, which provides a reference to the Java language. The opening page describes how to use
the API help. For the time being much of this will be difficult for you. We will briefly cover how to interpret
some features of this help later on.
http://java.sun.com/j2se/1.4/docs/api/index-files/index-1.html

The following page gives a listing of the various packages in Java.


http://java.sun.com/j2se/1.4/docs/api/index.html

Here is the first program

import java.applet.Applet; //Applet Class


import java.awt.*; //Graphics class

//An introductory class to illustrate the use of Graphics objects,Fonts and Colors.
//Paint (Graphics g) is one of the standard methods which is always used in a java applet.
//In this case we have added a few graphics to it.

public class PaintDemo extends Applet


{

//The paint method enables you to draw objects in the window

public void paint (Graphics g)


{
g.setFont(new Font("serif", Font.BOLD, 13)); //new Font
g.setColor(new Color(255,0,0)); //string will be red
g.drawString("Hello World",25,65); //method for drawing a string
g.setColor(new Color(0,255,0)); //rectangle will be green
g.drawRect(20,20,80,80); //method for drawing rectangle
g.setColor(new Color(0,0,255)); //oval will be blue
g.drawOval(20,20,80,80); //method for drawing an oval
g.setColor(Color.cyan); //predefined color constant
g.fillRect(20,110,80,40); //a filled rectangle.
}
}
Explanatory Notes on the “PaintDemo” class:

Packages
The Java Applications Programming Interface (API) contains a large number of programming
features grouped into “packages” of related features. When you write a class in Java you must
import those packages which are used in the class.

 The java.applet package is used in all classes in this course.


 The java.awt package is used to create the graphics used in the applet windows.

Class
We will have a lot more to say about classes in this course. For the time being, you can regard a class
as a program, and every class that you write will begin with the line:

public class <class name> extends Applet


Paint( )
A method is a section of code that does a particular job in a class. Methods (in Object Oriented
languages) are essentially the same as procedures and functions in other languages. They enable you
to break up a long piece of code into smaller more manageable modules. These methods can be used
many times in the original class and can be used in other classes.

One of the standard methods used in java applets is the paint( ) method. This is responsible for
painting graphics and text into the applet window.

If you want to use the paint method you always begin with the line:

public void paint (Graphics g)

Fonts
 The font names available are “Serif”, “SansSerif”, “Monospaced”.
 The font styles available are Font.PLAIN, Font.BOLD and Font.ITALIC.
 The font size is a whole number.

You can set a font in the paint() method with a line such as:

g.setFont ( new Font ( “Serif”, Font.BOLD, 14 ));

To find out more about fonts you can look up the the Java API following the links
Java API | Package Java awt | Classe Index Fonts.

You will notice that the awt package includes many more of the classes you would expect to use
such as Color.

Colors
Colors are most easily specified by their Red, Green and Blue RGB components, which are each
integers from 0 to 255.
You can set a colour in the paint( ) method with a line such as:

g.setColor ( new Color(255, 125, 0));

(This is a colour containing the maximum amount of red, about half green and no blue.)

Standard colours provided in java are:

Color.orange Color.pink Color.cyan Color.magenta


Color.yellow Color.black Color.white Color.gray
Color.lightGray Color.darkGray Color.red Color.green
Color.blue

To use these in paint( ) you use a programming line such as:

g.setColor(Color.green);

Window Coordinates
When you draw a graphics object on the applet window, you must specify its coordinates.

The top left corner of an applet window has coordinates (0,0).


Position from the top left is measured in pixels, and a typical window might be 800 pixels wide by
600 pixels high, so that it’s bottom right has coordinates (800, 600).

Strings
A string is a piece of text enclosed in inverted commas, such as “Hello”. To write a string onto the
applet window in paint() you use a programming line such as:

g.drawString(“Hello World”, 25, 60);

where the “x” coordinate is 25 and the “y” coordinate 60.

If you want to use a font other than the standard font you must set it before you use g.drawString.

Graphics Objects
The java.awt package provides a number of graphics objects. To find out all that are available, look
up the Java WorkShop Help under:

***Help | Java API Documentation | Package Java awt | Class Index | Graphics

Some graphics objects that you are likely to use are:

g.drawRect(<top left x coordinate>, <top left y coordinate>, <width>, <height>);


g.drawOval(Coordinates as for drawRect, with oval drawn inside the imaginary rectangle);
g.drawLine(x1, y1, x2, y2);
g.fillRect(as for drawRect);
Practical Exercise 1

1. Start Programs / Programming / RealJ

2. File / New Project / RealJProject / OK

3. Type in class name (in this case PaintDemo)

4. Select the Applet Project radio button (in this course we will be dealing with Applets only)

5. Delete unwanted code from the default class that appears on the screen and type in the above
PaintDemo class. Remember that Java is CASE SENSITIVE so be careful to retain the case (ie
upper or lower case) as written above.

6. Save the class (you must have a Java file)

7. Click the BUILD BUTTON

8. If you have errors – check you uppercase / lower case / spelling etc. Most problems will occur
from small spelling mistakes.

9. If no errors press the RUN APPLET button and you should see the following:
10. Now modify the class to suit your own tastes: you should try

 Changing the font type, style and size.


 Changing the text.
 Adding some new graphics objects as outlined in the ***Java API help.

11. Try to produce the following with a font size of 80, red text “ELLO”, white text “H” and a blue
rectangle behind the “H”:

When you have completed this check with your teacher.


Introductory Exercise 2 -Integer Variables

Introduces
 int (integer) variables
 the init() method
 basic integer operations
 g.drawString used to print out integer values

import java.applet.Applet;
import java.awt.*;

public class IntegerDemo extends Applet


{

// Globally declare two integers and variable names for their sum, difference,
// product, quotient and remainder.

int n, m, sum, diff, prod, quot, remainder;

public void init()


{

n = 25; //initialise values of n and m.


m = 6;
sum = n + m; //These calculations could be carried out in paint() or in init.
diff = n - m; //Because the variables have been declared globally, the values
prod = n*m; //can be transferred between the methods paint() and init().
quot = n/m;
remainder = n%m;
}

public void paint (Graphics g)


{
g.drawString("The original values are " + n + " and " + m, 25, 25);
g.drawString("The sum is " + sum, 25, 50);
g.drawString("The difference is " + diff, 25, 75);
g.drawString("The product is " + prod, 25, 100);
g.drawString("The quotient is " + quot, 25, 125);
g.drawString("The remainder is " + remainder, 25, 150);
}
}

Notes

Variables
Variables are spaces in computer memory which store things such as numbers and characters.
When you declare a variable you tell the class what type of variable it is (eg integer or real number)
and give it a name. The class then sets aside the appropriate memory space for the variable, so that
you can use this throughout the class.

To declare an integer variable you use a line such as:

int n; //for one integer variable


int n, m, sum; //for a number of different integer variables.
Variable names can contain letters and digits, and (by convention) start with a lower case letter.

A global declaration (immediately after the main class definition) means that all the “methods” of
the class can use these variables and their values.
Basic integer operations
 Assignment:
n = 4; //assigns the value 4 to variable n
 Sum:
sum = 4 + 7; //the variable sum is assigned the value 4 + 7
sum = n + 4; //variable sum becomes n + 4 where n is another integer variable.
 Product:
prod = n * 4; //variable prod is assigned the value n*4
 Integer division:
quot = n / 4; //eg 7/4 = 1; 13/4 = 3 etc
 Integer remainder or “modulus”:
rem = n%4; //eg 7%4 = 3; 13%4 = 1 etc

The init() method


Like paint(), this is another standard applet method. It is used by the programmer to set up the initial
conditions of a class. In this case it is give values to all of the variables that will be printed out in the
paint() method.

Breaking up the class into different methods in this way makes the class much easier to manage and
more versatile.

Writing the integer values to the applet window


The paint() method can use a line such as:

g.drawString("The sum is " + sum, 25, 50);

to write out the value of the variable. Note that to use drawString in this manner you must precede
the integer by a string.

Practical Exercise 2

1. Type out the above class in a new project.


2. Tell the class to work out and print the values of:
(n + m) / (n – m)
(n + m) * (n – m)
n + n/m
n/m + n
n/(m+n)

You might wish to declare new variable names for each of these quantities.
Theoretical Exercise 2

There are about 12 mistakes in the following class. How many can you identify?
(Lines are numbered for convenience in answering.)

1. import java.applet.Applet;
2. import java.awt.*;

3. public class IntegerDemo extends applet


4. {

5. int n, m, sum;

6. public void init


7. {
8. n = 25; /initialise values of n and m.
9. m = 6;
10. sum = n + m;
11. diff = n - m
12. }

13. public void paint (Graphics)


14. {
15. g.setFont(new Font("Serif", Font.bold));
16. g.setColor(Color(255,0,0));
17. g.drawString("The original values are " + n + and + m, 25, 25);
18. g.drawString("The sum is " + sum, 25, 50);
19. g.drawString("The difference is " + diff, 25, 75);
20. }
21.}
Introductory Exercises 3 - Objects

Introduces
 Declaring and instantiating global color and font objects.

import java.applet.Applet;
import java.awt;

//This class is a development of the PaintDemo class in introductory exercise 1. It


//demonstrates simple Graphics with colors and fonts declared and then instantiated in init.

public class ObjectDemo extends Applet


{

// This class is similar to the PaintDemo class except that the init method (another standard
// method used in java applets) is used to initialise the colors and fonts used in paint.
// To transfer the information from init to paint we must first declare the color and font as
// "objects" that can be accessed in both paint and init.

Color color1, color2, color3; //declare three colors


Font font1; //declare a font

//The init method is used in this case to set some global colours and fonts.

public void init()


{
setBackground(Color.yellow); //background color
color1 = new Color(255,50, 50); //instantiate color1
color2 = new Color(50, 255,50); //instantiate color2
color3 = new Color(50, 50, 255); //instantiate color3
font1 = new Font("SansSerif", Font.ITALIC, 14); //instantiate font1
}

//The paint method can now make use of the colours and fonts defined in init().

public void paint (Graphics g)


{
g.setColor(color1);
g.drawRect(20,20,120,60);
g.setColor(color2);
g.fillOval(20,20,120,60);
g.setColor (color3);
g.setFont(font1);
g.drawString("Hello World", 50, 50);
}
}

Objects
Objects are the basic “modules” of an object oriented program. In the above class, color1, color2,
color3 and font1 are objects. Objects are stored in memory like variables, but have many more
features than variables.

Objects include
 data (such as the RGB values of the color objects in the above class)
 “methods” or operations on that data (such as the setColor method).
When objects are used in a class they must be set up in memory. This is called “instantiating” the
object.
Setting up objects in a class
In the first class we used a class line such as

g.setColor ( new Color(255, 125, 0));

to “instantiate” a new colour and “set” it as the current graphics colour.

When we do this we set the new colour as an object in memory. However, this new colour is only
used until the next new colour is set. If we have a colour that we want to use on different occasions,
we must declare the colour by giving it a name before we instantiate it.

We declare the colours we a going to use with a program line such as:

Color color1, color2, color3;

When we want to give the colour a value in memory (“instantiate” the color) we use the new
command:
color1 = new Color(255, 50, 50);

We can now set out new colour in the paint() method with a program line such as:
g.setColor(color1);

Global declaration of the objects


In this class, we declared the colour and font objects immediately after the main class definition. By
declaring the objects inside the main class in this way, they become available to all the methods used
in the class. This means that we can instantiate the objects in the init() method and then set the same
objects in the paint() method.

When the objects are made available to the whole class in this way we say that they are declared
globally.

Practical Exercise 3

1. Copy and run the above class as before. Be sure to give your project the same name as the class
(in this case ObjectDemo).
2. Declare some new colour and font objects. Make up your own names for the objects (a
combination of letters and numbers).
3. Instantiate the objects in the init() method using new.
4. Set the objects in the paint() method and use them in your own applet.
5. Check with your teacher when finished.
Introductory Exercise 4 -Strings

Introduces
 The String class
 Various methods of constructing string
 String methods length(), toUpperCase(), toLowerCase(), trim(), replace().

The String class is contained in the java.lang package which is automatically called for all classes (so
that it does not need to be imported).

import java.applet.Applet;
import java.awt.*;

// This simple class introduces simple string ideas.


// Strings are objects and must be declared,instantiated and given values.
// However, there are some short cuts in setting up a string in a class.

public class StringDemo extends Applet


{

String s1, s2, s3, s4,


s5 = "How are you ."; //Strings can be initialised when declared

public void init()


{
s1 = new String (); //null string
s2 = new String ("Hello"); //one way to initialise with a value
s3 = new String (s2); //another way to initialise
s4 = " Hello "; //still another way.
}

public void paint (Graphics g)


{
//The following line illustrates concatenation of strings with +
g.drawString(s2 + " What a nice day.", 25,25);

//The following line illustrates the string method length


g.drawString("s2 equals " + s2, 25, 50);
g.drawString("Length of s2 is " + s2.length() + " characters", 25,75);

//Uppercase and lowercase methods. In these examples, we have not


//declared a name for the new strings, so that the new string is
//lost as soon as the drawString method is over.
g.drawString("s2 to UpperCase is " + s2.toUpperCase(), 25, 100);
g.drawString("s2 to LowerCase is " + s2.toLowerCase(), 25,125);

//Trim removes the white spaces on either side of the string.


//In this example (and the next) we have named the new strings
//so that the new string remains after the drawString method.
s1 = s4.trim();
g.drawString("The original s4 is:" + s4, 25, 150);
g.drawString("After trimming s4 is:" + s1, 25,175);

//replace changes characters


s1 = s2.replace('H', 'h');
g.drawString("s2 after a replace is " + s1, 25, 200);
}
}
Strings
The String class produces String objects in a class.

Since Strings are objects, the normal way to set up a string in a class is to declare it and instantiate it
using new.

Eg String string1; //declaration section


string1 = new String (“Hello”); //init or other

However, Strings provide some short cuts:


You can initialise the String when you declare it:
String string1 = “Hello”; //declaration

You can give it a value directly after declaring it


string1 = “Hello”; //init or other

String methods
A number of the string methods are illustrated in the above class. These are:

len = s1.length(); //returns the number of characters in the string


s2 = s1.trim(); //s2 is a copy of s1 with all white characters removed from the
//beginning and end.
s2 = s1.toUpperCase; //s2 is a copy of s1 with all characters in upper case
s2 = s1.toLowerCase; //s2 is a copy of s1 with all characters in lower case.
s2 = s1.replace(‘H’, ‘h’); //s2 is a copy of s1 with all ‘H’ characters replaced by
//the ‘h’ character.

Practical Exercise 4

1. Copy and run the above class as before. Be sure to give your project the same name as the
class (in this case StringtDemo).
Introductory Exercise 5 - Components

Introduces
 Components (including Label, TextField and Button)
 The add operation

import java.applet.Applet;
import java.awt.*;

// Simple class to demonstrate the use of Graphics Components.


// It provides the user interface add to two numbers, WITHOUT actually doing the addition.
// The extended class to perform the addition is EventDemo.

public class ComponentDemo extends Applet


{

Label myPrompt1, myPrompt2; //declare prompts (Labels)


TextField value1, value2; //declare user input (text)
Button addButton; //declare a button to start addition

//The init method sets up the GUI components that have been declared globally.
//To do this we must:
// - "instantiate" the components using the "new" command. This provides space in
memory for the components.
// - "add" the components to the applet window, in the left to right, up to down order in
// which they are added in init.

public void init()


{
//instantiate components
myPrompt1 = new Label("This class will add two numbers.");
myPrompt2 = new Label("Type in the numbers in the spaces.");
value1 = new TextField(10); //width of TextField
value2 = new TextField(10);
addButton = new Button("Press to add"); //text in Button

//place components in the applet window in the order written left to right, then
//downwards.
add (myPrompt1);
add (myPrompt2);
add (value1);
add (value2);
add (addButton);
}
}

Notes
Components
Components are Graphical User Interface (GUI) objects which are used to provide an interface for
the user, enabling the user to enter data into the class. There are many such components, including
TextFields, Buttons, Menu, ScrollBar and so on. They are described under the Help | API | java.awt.
Setting up components in an applet window
To set up a component in an applet window you must:

1. Declare the component giving it a name which by convention starts with a lower case letter. A
typical declaration is:
Button myButton; //declares a Button object of name myButton

2. Instantiate the component using new. For example:


myButton = new Button(“<name printed on button>”);

3. Add the component to the window. For example:


add ( myButton);

The components are placed in the applet window in the order in which they are added, left to right
and top to bottom.

Controlling the layout of the window


While there are more sophisticated methods for controlling the layout of a window, for the time
being you can set the position of the components by
1. adjusting the size of the components (by changing the text etc)
2. adjusting the size of the applet window. To do this go to main menu | Project | Edit | Run and
adjust the width and height of the window.

Practical Exercise 5

Copy out the class into a new project and adjust the size of the components and the window to give
you a good layout.

At this stage you can type into the text fields, but it won’t do anything.
Introductory Exercise 6 - Events
Introduces
 java.awt.event.*
 ActionListener and actionPerformed (ActionEvent e)
 Converting text to integer using Integer.parseInt and Integer.valueOf
 Converting integer to text using Integer.toString
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*; //Handles events initiated by the user

// This class extends the previous class ComponentDemo to actually provide a means of adding
// up the numbers. It does this by including an Action Event method.
// Additions to ComponentDemo are in bold type.

//The class definition includes "implements ActionListener which tells the class to "listen"
for //"events" set of by the user.
// In this case, the event being listened to is the press of a "button in the applet window.

public class EventDemo extends Applet implements ActionListener


{

Label myPrompt1, myPrompt2;


TextField value1, value2;
Button addButton;
int num1, num2, answer; //integers displayed in text fields and their sum

public void init()


{
myPrompt1 = new Label("This class will add two numbers.");
myPrompt2 = new Label("Type in the numbers in the spaces.");
value1 = new TextField(10);
value2 = new TextField(10);
addButton = new Button("Press to add");
add (myPrompt1);
add (myPrompt2);
add (value1);
add (value2);
add (addButton);
addButton.addActionListener(this); //Tell the class which event to listen to:
}

//The method "actionPerformed (ActionEvent e)" is used to "listen" to events and respond
public void actionPerformed(ActionEvent e)
{
//The user must type the integers into the text fields. When the button is pressed,
// - the text field strings are converted to integers (two different methods are
// provided – they do the same job.
// - the integers are added together
// - the sum is displayed in the status bar.

num1 = Integer.parseInt(value1.getText()); //Convert text value1 and value2


num2 = Integer.valueOf(value2.getText()).intValue();
answer = num1 + num2; //Find the sum
showStatus(Integer.toString(answer)); //Display the sum
repaint();
}
}
Events
An event is an action performed by the user which gives information to the class. GUI components
are often used to generate events. Events can include things such as
 Clicking a Button, List, CheckBox etc.
 Pressing <return> with the mouse cursor in a Text Field.
 Clicking or moving a mouse.

If we want the class to “listen” to events, we have to

1. Tell the class to implement ActionListener:


public class <ClassName> extends Applet implements ActionListener {

2. Tell the class which events to listen to (there might be a number of possible events):
addButton.addActionListener(this);

In this case, we are telling the class to listen to the GUI component that we have named
“addButton”. The word this tells the class that “this” class is doing the listening (it is possible to
listen to events in other classes).

3. Use the actionPerformed method to do the listening:


public void actionPerformed(ActionEvent e)

Converting integers to strings and strings to integers


When you type into a Text Field, the information is stored as a string or series of characters. If you
are typing in a number, you must convert the string to a number with a class line such as one of the
following (which do the same job):
num1 = Integer.parseInt(value1.getText());
num2 = Integer.valueOf(value2.getText()).intValue();

 Here parseInt is one of the methods of the Integer class, which converts a string to an integer.
 valueOf is another method of the Integer class. We won’t worry about the details of this
approach for the time being and you will probably prefer to use parseInt in your classs.
 getText is one of the methods of the TextField class which retrieves the text from the Text Field.

An integer must be converted back to a string to print it out on the window. One way to do this is to
concatenate the number to a string as we did in the second exercise.

g.drawString(“The value is “ + num, 25, 50);

However, to print out the number without a preceeding string you need to use the toString method
first in a line such as:

g.drawString(Integer.toString ( num ), 25, 50);

If there is only one answer to print out, we can avoid using paint() by printing the answer in the
status bar at the bottom of the applet window, using the line:

showStatus(Integer.toString(answer));
Practical Exercise 6

1. Copy and paste the ComponentDemo class into a new EventDemo project and modify it as
above.
2. Modify the class to:
 Print out the answer within the window (using paint()).
 Print out the product of the numbers instead of the sum.
3. Allow the class to listen to a press of the <return> key when the cursor is in one of the Text
Fields by adding the following programming lines to init():

value1.addActionListener(this);
value2.addActionListener(this);

Theoretical Exercise 6

Find the mistakes in the following class. As well as this


 What is displayed in the applet window, and what code should you add to display everything that
ought to be displayed?
 What events does the applet listen to? What code should you add so that it listens to everything it
ought to listen to?

1 import java.applet.Applet;
2 import java.awt.*;

3 public class EventDemo extends Applet implements ActionListener


4 {

5 Label myPrompt;
6 TextField value1, value2;
7 int num1, num2, answer;

8 public void init()


9 {
10 myPrompt = new Label("This class will multiply two numbers.");
11 value1 = new TextField(10);
12 addButton = new Button(Press to add);
13 add (myPrompt1);
14 add (value1);
15 add (addButton);
16 addButton.addActionListener(this);
17 value1.addActionListener(this);
18 }

19 public void actionPerformed(ActionEvent e)


20 {

21 num1 = Integer.parseInt(value1.getText);
22 num2 = Integer.valueOf(value2.getText).intValue();
23 answer = num1 * num2;
24 showStatus(answer);
25 }
26 }
Introductory Exercise 7 -Images
Introduces
 Image objects
 getImage, getDocumentBase, drawImage methods.

import java.applet.Applet;
import java.awt.*;

public class ImageDemo extends Applet


{
Image butterfly, picture; //image variable

public void init()


{

//Next line gets an image stored in the same directory as the HTML.
//These images can be imported or created in Paint Shop Pro.

butterfly = getImage(getDocumentBase(),"butterfly.gif");
picture = getImage(getDocumentBase(), "picture.gif");
}

public void paint(Graphics g)


{
//The later images are drawn on top of the earlier ones.
g.drawImage(picture, 50, 60, this);

int width = butterfly.getWidth(this); //width of butterfly image


int height = butterfly.getHeight(this); //height of butterfly image

//Draw butterfly scaled two times on top of picture


g.drawImage(butterfly, 130, 250, width*2, height*2, this);
}
}

Getting an image
You can draw any gif image onto your applet window. To obtain a gif image, have a look in Paint
Shop Pro (on your computers) and either import an image or create one.

An image is an object which you must


1. Declare : Image <image1>, <image2>, ….. ;
2. Instantiate : To do this, you need to tell the class the name of the image file and where it is. For
the time being you should store all images in the same directory as your project files.
The method getDocumentBase() gives the directory of the html file in your project and
getCodeBase() gives the directory of the class file – both of which are the same if you are using
a Java WorkShop project.
The method getImage places the image in your class.
Painting an image
To paint the image in the window you use one of the drawImage methods of paint().

The simplest of these methods is illustrated by:

g.drawImage(picture, 50, 60, this);

where the two numbers are the x and y coordinates of the top left of the image, and “this” again tells
the class to draw the image in this applet.

Another draw image method allows you to specify the width and height of the image drawn in the
window :

g.drawImage(butterfly, 130, 250, width*2, height*2, this);

Here the 4th and 5th parameters tell the class the width and height of the image on the window. In the
class above we used the getWidth and getHeight methods to find the width and height of the
original image and then multiply these by two so that the final drawn image was twice the size of the
original.

Practical Exercise 7

Have a bit of fun, and remember that you will eventually be incorporating java applets in web pages.
Use Paint Shop Pro to draw or import some images which you can then put into the applet.
Introductory Exercise 8 -Sound
Introduces
 The play method
 AudioClip class and method getAudioClip

//This very simple class will play an audio file of type .au stored in the same folder as the //
SoundDemo project. It will play the sound once only.

import java.applet.Applet;

public class SoundDemo extends Applet


{

public void init()


{
play (getCodeBase(), "gong.au");
}
}

Notes
The sound file formats supported by Java 2 include files ending with .au, .wav, .midi, and .aiff. You
can find suitable files if you do a search for *.au or *.wav.
Au files can be found at C:\Java-WorkShop20\JWS\examples\ClockBeans.
There are plenty of wav files at c:\winnt\media\Microsoft office 2000.

Java applets can play sound files using the play method.

In the above simple class, the sound is played once only.

Practical Exercise 8a

 Set up a project SoundDemo and move one of the au files into the project directory. Run the class
on a computer with a sound card.
 Modify the class so that the sound plays when the user clicks an appropriate button.
More Sound
Here is an extended version of the above program which enables you to have a lot more control of
the sound. It does this by declaring the sound file as a named object. The loop() and stop() methods
can then be applied to this sound.

The code also introduces “if” statements (which enable you to make a choice) and the getSource()
method (which enables you to determine which button has been pressed). More on these later.

Although the class does not use it, you could also have the code play(glass) to play the sound once as
in the previous class.

import java.awt.*;
import java.applet.*; //import all (*) imports AudioClip class
import java.awt.event.*;
//To run this you will need to put in some sound files (.au or .wav) into the
//same directory as your project.
//In this case a .wav file is used

public class SoundDemo extends Applet implements ActionListener


{
Button playSound, stopSound; //To play and stop sound
AudioClip tada, glass; //Declaring the sound files

public void init()


{
stopSound = new Button("Stop sound");
add(stopSound);
stopSound.addActionListener (this);

glass = getAudioClip(getCodeBase(), "breaking glass.wav");


playSound = new Button ("Play Sound");
add (playSound);
playSound.addActionListener (this);

public void actionPerformed(ActionEvent e)


{
//We will be doing "if" statements and getSource() in more detail
//later. In this case we have to determine a course of action
//depending on the button which has been pressed.
if (e.getSource() == playSound) glass.loop();
else glass.stop();
}
}

Practical Exercise 8b

Modify your previous class to get the above class going.


Introductory Exercise 9 -More on numbers and strings
Introduces
 Double variable type (one of the real number types)
 DecimalFormat class
 Various ways of converting between numbers and strings (including some revision).

import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;

//This class demonstrates methods for converting text to numerical values and converting the
// numerical values back to text for printing in paint.
// It also shows different ways of instantiating strings.

public class NumberDemo extends Applet


{
String s1, s2; //numerical strings for integers
String s3 = “76.5156”; //Strings can be initialised on declaration
int int1, int2; //corresponding values for integers
double real1; //corresponding values for reals
DecimalFormat precision2; //set decimal format for reals

public void init()


{
//Define two strings which will be converted to numbers.
s1 = new String( "1256" ); //instantiate s1
s2 = "5678"; //Strings can be instantiated directly

//Define a decimal format of two decimal places (rounded)


precision2 = new DecimalFormat("#.00");

int1 = Integer.parseInt(s1); //One way to convert string to integer


int2 = Integer.valueOf(s2).intValue(); //Another way
real1 = Double.valueOf(s3).doubleValue(); //Convert string to double
}
public void paint (Graphics g)
{
//Using drawString to “paint” the string values of the numbers.
g.drawString(Integer.toString(int1), 25, 25);
g.drawString(Integer.toString(int2), 25, 50);
g.drawString(Double.toString(real1), 25, 75);
g.drawString(precision2.format(real1), 25, 100);
}
}

Revision
In Introductory Exercise 2 (IntegerDemo) we looked at one technique for painting integer values in
the applet window. This involved concatenating the integer with a string. For example:

g.drawString(“The answer is “ + ans, 25, 50);


In Introductory Exercise 6 (EventDemo) we noted that the above technique of painting integer values
does not work if the integer is not preceeded by a string. To paint an integer directly we had to
convert it to a string. For example:
g.drawString(Integer.toString(int1), 25, 25);

We also used the reverse process, converting a string to an integer, in the EventDemo class.
num1 = Integer.parseInt(value1.getText());
num2 = Integer.valueOf(value2.getText()).intValue();

This technique works for any integer type string. For example:
num1 = Integer.parseInt(“12345”);

Converting between strings and doubles


Doubles are one of the java real types. The next class deals more with reals.

To convert a string to a double we use, for example:

real1 = Double.valueOf(s3).doubleValue();

To paint a double as a string with full precision (all decimal places) we use, for example:

g.drawString(Double.toString(real1), 25, 75);

To paint a double with the required number of decimal places uses the DecimalFormat class. To use
this we must declare a particular decimal format as an object (for example precision2 in the above
class), instantiate it giving it its value and then use it in the paint() method. In the above class the
relevant class lines were:

DecimalFormat precision2; //declare DecimalFormat object


precision2 = new DecimalFormat("#.00"); //instantiate
g.drawString(precision2.format(real1), 25, 100); //Use format method in paint()

Practical Exercises 9
Type in, and get the above class going.
Introductory Exercise 10 - Real numbers (and more!)
Introduces
 The float and double types together with methods round, sqrt, max and random.
 Promoting a number in a binary operation.
 Casting using (int) and (double).
import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;

// The basic number information is in the package java.lang which does not have to be imported
// (although decimal formatting is in the text.DecimalFormat class and must be imported.)
// This class illustrates some of the methods and techniques in the Math, Float, Double and
// Integer classes within the java.lang class.

public class RealDemo extends Applet {

//We can declare and initialise numbers at the same time. Note that a float (which occupies less
//memory space than a double) must be followed by f when initialised.

float f = 2.345f;
double d = 5.678;
double prod, quot;
double e = 1.456E+45;
int i;
DecimalFormat precision2;

public void init()


{
precision2 = new DecimalFormat("#0.00");
}

public void paint (Graphics g)


{

//Printing out some real values.


g.drawString("Float = " + f, 25, 50);
g.drawString("Double = " + d, 25, 75);
g.drawString("Precise product is " + (f*d), 25, 100);
g.drawString("Rounded product is " + precision2.format(f*d), 25, 125);
g.drawString("Exponent value is " + e, 25, 150);
g.drawString("Exponent times float is " + e*f, 25, 175);

//Some methods in the double and float classes


g.drawString("Float rounded is " + Math.round(f), 25, 200);
g.drawString("Double rounded is " + Math.round(d), 25, 225);
g.drawString("Square root of float is " + Math.sqrt(f), 25,250);
g.drawString("The largest of f and d is " + Math.max(f,d), 25, 275);
g.drawString("A random real from 0 to 1 is " + Math.random(), 25, 300);

//Some uses of casts (int) and (double)


g.drawString("Integer value of float " + f + " is " + (int)(f), 25, 350);
g.drawString("Integer value of double " + d + " is " + (int)(d), 25, 375);
g.drawString("A random integer (1 to 100) is "+(int)(Math.random()*100+1),25,400);
g.drawString("Integer value of 33/7 is " + (33/7), 25, 425);
g.drawString("Double value of 33/7 is " + (double)33/7, 25, 450);
}
}
Number Types
The standard number types covered in the java.lang class are:

int about –2.15 x 109 to + 2.15 x 109

long about –9.22 x 1018 to + 9.22 x 109

float about –3.4 x 1038 to + 3.4 x 1038 (written as –3.4E+38 to 3.4E+38)

double about –1.80 x 10308 to +1.8 x 10308 (written as –1.8E+308 to 1.8E+308)

Precedence of Mathematical Operations


The order of precedence of standard mathematical operations is
() parentheses if more than one set of parentheses evaluated left to right
*/% if more than one operation, evaluated left to right
+- if more than one operation, evaluated left to right

Mathematics Methods
To obtain a full listing of standard mathematical methods that are available in all classes look at the
API help under java.lang.Math. Note that methods of the same name may be defined for different
types (int, long, float, double). Some of those used in the above class:

Math.round(float / double) rounds to the nearest integer


Math.sqrt(double) square root
Math.max(int, int) etc the maximum value of the two (for all types)
Math.random() a random double from 0 to 1.0

Promoting
Java can only perform binary operations (such as + * - /) on two numbers of the same type. For
example, if you want to multiply an integer by a double, it will first promote the integer to a double
to give a double answer.

For example 4 * 3.1 is converted to 4.0 * 3.1 to give a final answer of 12.4.
The order of promotion for numbers is: int  long  float  double.

Casting
There are some situations in which you want to convert one number type to another. You can do this
by using a cast such as (int), (double) etc.

Two important examples of casting are provided in the above class.


 To convert a float or double to an integer use the (int) cast: In the above example a random
double was converted to an integer.
 To convert an integer to a double use the (double) cast. In the above example, the result of 33/7 is
the integer 4. If you convert 33 to a double 33.0 using (double) 33, the result of the division 33/7
is also a double – this time of value 4.714…. Note that the result of (double) (33/7) is the double
value of the integer 4, which is 4.0.
Theoretical Exercise 10

1. What are the values (as calculated by Java) of the following expressions. Be careful to indicate
the difference between an integer (int or long) and a real (float or double) answer.
(You will have to look up the API help under java.lang.Math for some of these.)

(a) 4 + 2*3 (l) 4 + 10%3


(b) (4 + 2)*3 (m) 11%3 * 5
(c) 10/4 (n) 11 * 3%5
(d) (double) 10 (o) 11 * (3%5)
(e) (double) 10 / 4 (p) Math.sqrt(16)
(f) (double) (10/4) (q) Math.abs(-7)
(g) (int) 25.67 (r) Math.abs(-14.4)
(h) Math.round(25.67) (s) Math.max(4, 8);
(i) 4*4 (t) Math.min(3.6, -4.5)
(j) 4 * 4.0 (u) Math.pow(2, 3)
(k) 4 + 10/3 (v) Math.sin(PI / 2)
(w)

2. What are the final values of m after the following java statements are executed, if m has an initial
value of 20.

(a) m = m + 5; (f) m%=6;


(b) m ++; (g) m *= 3.0;
(c) m --; (h) m /= 6;
(d) m += 10; (i) m /= 6.0;
(e) m -= 12;

Answers
1 a)10 b)18 c)2 d)10.0 e)2.5 f)2.0 g)25 h)26 i)16 j)16.0 k)7 l)5
m)10 n)3 0)33 p)4 q)7 r)14.4 s)8 t)-4.5 u)8 v)1
2 a)25 b)21 c)19 d)30 e)8 f)2 g)60.0 h)3 i)3.333..

Practical Exercises 10
Sample solutions are provided in Outlook

1. Write a class that lets the user enter two real numbers and prints out their sum, product,
quotient and the maximum value. (Ex10_1_Reals)
2. Write a class that has a counter button: the class counts each time the user presses the button
and prints this out. (Ex10_2_Count)
Introductory Exercise 11 - The if statement
Introduces
 The if statement
 Brackets around multiple statements.
 Equality and relational operators
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

//This class is a modification of the previous addition class, but instead of adding the two
//numbers it compares them with using an if conditional statement.
public class IfDemo extends Applet implements ActionListener
{
Label myPrompt1, myPrompt2; //declare prompts (Labels)
TextField value1, value2; //declare user input (text)
int num1, num2; //integers displayed in text fields

public void init()


{
//instantiate and add components as in previous class
myPrompt1 = new Label("This class will compare two numbers.");
myPrompt2 = new Label("Type in the numbers in the spaces.");
value1 = new TextField(10);
value2 = new TextField(10);
add (myPrompt1);
add (myPrompt2);
add (value1);
add (value2);
//We must now tell the class which events to listen to:
value1.addActionListener(this);
value2.addActionListener(this);
}

//ActionPerformed is here used simply to get the values of the two integers
public void actionPerformed(ActionEvent e)
{
num1 = Integer.parseInt(value1.getText());
num2 = Integer.parseInt(value2.getText());
repaint();
}

//paint is used to print out the comparison between the two numbers. An alternate
//approach would be to use showStatus in the actionPerformed method.
public void paint (Graphics g)
{
if (num1 > num2)
{
g.drawString("First number is larger.", 25, 150);
g.drawString(“Maximum value is “ + num1, 25, 200);
}
if (num1 == num2) g.drawString("Numbers are equal.", 25, 150);
if (num1 < num2)
{
g.drawString("First number is smaller.", 25, 150);
g.drawString(“Maximum value is “ + num2, 25, 200);
}
}
}
Equality and Relational Operators

Equality operators
== x == y x is equal to y
!= x != y x is not equal to y

Relational operators
> x>y x is greater than y
< x<y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y

The if statement
An if statement has one of the general forms:

if (<boolean expression>) <statement>; //single statement

if (<boolean expression>) { //multiple statements


Statement1;
Statement2;
<More statements>
}

The boolean expression is any statement that has values true or false. The simplest boolean
expressions use one of the equality or relational operators.

Note that when an if statement is to implement more than one statements, these multiple statements
must be enclosed in { } parentheses. If this is not done only the first of the multiple statements is
controlled by the if statement.

While the position of the parentheses does not matter so far as the class is concerned, you will
frequently line up the final } parenthesis with the preceding if (as is done in the class above).

Practical Exercises 11

From now on the practical exercises get more interesting – and harder! Specimen solutions are
posted in Outlook: you should check these only when you are having trouble.

11.1 Guessing Game (Sample solution Ex 11_1_Guess)


Write a class that will
 Determine a random integer between 0 and 99
 Ask the user to type in a guess.
 Tell the user if his guess is greater than, equal to or less than the number chosen by the computer.
A good class will print out the value of the last guess.
 Once you have got this going, keep track of how many guesses the user has had before getting
the correct answer. Print this out.
 Add a button to reset the game, that is, get a new random number and set the count back to zero.

11.2 Salaries (Sample solution Ex 11_2_Salary)


Write a class to calculate the wages owing to a worker given the following rules.
 If the total hours worked is less than 35, the hourly rate is $15 per hour.
 If the total hours worked is more than 35, the hours in excess of 35 earn a rate of $25 per hour.

Your class should have a Text Field for the user to enter the total number of hours worked.

11.3 Maximum (Sample solution Ex 11_3_Maximum)


Write a class to determine the maximum value of three different integers. Once way to do this is to make
clever use of the Math.max method. However, try also doing this by
 Declaring a variable, say maximum, that is to equal the maximum value.
 Using a series of if statements, set maximum to the larges of each of the three integers.

To begin with, you could just initialise the three integers in your class. However, once you have done this you
should provide three text boxes for the user to input the numbers.

11.4 Getting numbers in order (Sample solution Ex 11_4_Order)


Write a class to place three integers in order smallest to largest.

This is a classic “ordering” problem and there are many ways of tackling it. Once suggested way is to proceed
as follows:
How to use temp:
Suppose the three values are initially called a, b and c. if (a > b)
 If a > b reverse them using a temporary variable called temp {
temp = a;
 If b > c reverse them using temp again.
a = b;
 If a > b again reverse them using temp. b = temp;
 Now a, b and c stand for the values in order and they can be }
printed out.

11.5 Triangles (Sample solution Ex 11_5_Triangle)


The user types in three numbers and you must decide whether they can form the sides of a triangle, and if so
whether the triangle is equilateral, isoceles or scalene.

Proceed as follows:

 Use the method above to place the sides of the triangles in order.
 If the smallest number is less than or equal to zero, or if the sum of the two smallest is less than the
largest, the numbers do not form a valid triangle.
 If all three sides are the same the triangle is equilateral. If two only are the same, the triangle is isoceles.

Once again, your final version of the class should include text fields for the users to type in data.
Introductory Exercise 12 - if else statements
Introduces
 if ..else statements
 the getSource() method of the event class (in Programming Exercise 3)

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

//User enters values from 0 ..49 and class counts values in ranges 0..9, 10..19 etc.

public class IfElseDemo extends Applet implements ActionListener {

int number, zeros, tens, twenties, thirties, forties;


Label prompt;
TextField value;

public void init()


{
zeros = 0; //Initialise all range counts.
tens = 0;
twenties = 0;
thirties = 0;
forties = 0;
prompt = new Label("Enter a number between 0 and 49");
value = new TextField(10);
add (prompt);
add (value);

value.addActionListener(this);
}

//Class tests if values are between 0..9, then 10..19 etc to 40..49 and maintains
//a tally of each the total number of entries within each range.
public void actionPerformed (ActionEvent e)
{
number = Integer.parseInt(value.getText());
if (number < 10) zeros = zeros + 1;
else
if (number < 20) tens = tens + 1;
else
if (number < 30) twenties = twenties + 1;
else
if (number < 40) thirties = thirties + 1;
else forties = forties + 1;
value.setText(""); //Clear the text box
repaint();
}

public void paint (Graphics g)


{
g.drawString ("Values 0 to 9 " + zeros, 25, 50);
g.drawString ("Values 10 to 19 " + tens, 25, 75);
g.drawString ("Values 20 to 29 " + twenties, 25, 100);
g.drawString ("Values 30 to 39 " + thirties, 25, 125);
g.drawString ("Values 40 to 49 " + forties, 25, 150);
}
}
Why use if .. else statements
With a series of if statements, every condition is tested every time the class is run. However, if these are
grouped into a long if .. else statement, the class exits the statement as soon as it finds the first true condition.
Some consequences are:

1. If there is only one desired true condition, using an if .. else statement makes the class more efficient
because those conditions after the first true condition are not tested.
2. Because the class exits from an if .. else statement as soon as there is a true condition, you can use what
would otherwise be overlapping conditions. For example in the above class, if number was 25 the if .. else
statement would exit on the third condition (number < 30) even though the remaining conditions (number
< 40 and number < 50) were true.

Programming exercises 12

(As before, sample solutions for these exercises are available on Outlook.)

12.1 Marks (Sample solution Ex 12_1_Marks)


A text field allows the use to enter the marks (out of 100) obtained by each of the students in a class. The
class keeps (and prints out) a tally of the number of students who gained an “A” (over 85), a “B” (over
70), a “C” (over 45), a “D” less than or equal to 45.

12.2 Histogram (Sample solution Ex 12_2_Histogram)


Get the class on the previous page running.

Draw a histogram of the data: this will be a series of rectangles of height proportional to the value of
zeros, ones …forties. To get a decent scale, you will need to multiply the zeros, ones etc values by a
constant scale factor which might be something like 20 (so that the height of each rectangle is 20 * <the
value of zeros, ones etc> pixels.

12.3 Voting (more on the getSource() method) (Sample solution Ex 12_3_Vote)


Write a class to determine which of four people wins a vote. Each time a button is clicked, the count for
that person is increased by one.
This will need a new technique in event handling.
In init(), listen to events prompted by each of the four buttons.
In ActionListener, you have to know which button has been pressed. To do this you need to use the
getSource() method of the event class. For example, if one of the people is named Jim, jim is the number
of votes for Jim and jimButton is Jim’s voting button, the following class line responds to a press of the
Jim button and increments Jim’s vote by one:

if (e.getSource() == jimButton) jim ++;

Finally, once you have counted up the total number of votes for each person you will have to work out
which of these is the largest. You should use the techniques of the previous Introductory Exercise 10 to do
this. Print out the names of all the people who have the largest vote (you may get more than one with the
top vote).

12.4 Calculator (Sample solution Ex 12_4_Calculator)


Produce a class that has two text fields and four calculator buttons for + - * /. The user types values into
the text fields and then clicks on one of the calculator buttons to determine which calculation to perform
on the numbers.

Once again, you will need to use the getSource to determine which button was pressed.
Introductory Exercise 13 The for loop

Introduces
 The for loop in its simplest form

import java.applet.Applet;
import java.awt.*;

//A simple demonstration of a for loop used to draw up a 6 times table.

public class ForDemo extends Applet


{
public void paint (Graphics g)
{
//For values of an int I from 1, 2, .., 12 the loop evaluates 6*i.
//Note that the for loop variable can be defined in the loop.
//Note also that the loop variable is used to position the printout.

for (int i = 1; i <=12; i ++)


g.drawString("6 times " + i + " = " + 6*i, 25, 25+20*i);
}
}

The for loop


A for loop allows you to repeat a programming sequence until some condition is met. The for loop
can be expressed as:

for (expression1 ; expression2 ; expression3 ) <statement>

where, in the simplest form of the for loop:


 expression1 gives the starting value of the control variable. As I the above example, you can
declare and initialise the control variable in this expression.
 expression2 is a boolean expression which gives you the final value of the control variable.
 expression3 tells the class how to change the control variable each time around the loop.
 The <statement> (which could be a compound statement enclosed in { } brackets) is repeated
each time the loop is executed.

In the above example, the control variable


 is an integer with initial value equal to 1
 must be less than or equal to 12
 is incremented by 1 each time around the loop.

As we will see later, the for loop can contain quite complex control expressions that do a lot more
than simply count.
Programming exercises 13

13.1 Sum and Factorial (Sample solution Ex 13_1_Sum)


Ask the user to input a positive whole number n and evaluate the
 sum 1 + 2 + ….. + n.
 the factorial 1 * 2 * … * n

13.2 Compound Interest (Sample solution Ex 13_2_Interest)


Do a simple compound interest calculation as follows:
Ask the user to input a principle, a monthly interest rate and a total period in months. The
principal could be any sensible value (such as 10000) and the interest rate could be a value
somewhere between 0.5% = 0.005 and 1.5% = 0.015 (say).
After each month the principle becomes principle * (1 + interest), and the class prints out the
total principle at the end of the period.

13.3 Print out a 12 times table


a) Including duplicate entries (Sample solution Ex 13_3_Table)
b) Without duplicate entries (Sample solution Ex 13_3_Table1)
You will need to be careful with your g.drawstring position

13.4 Ask the user to input a whole number between 1 and say 50. The class prints out a line of this
number of stars.
Exercise 14 Variables in Java
Variables are spaces in computer memory which store things such as numbers and characters.

Variable types
The variable types available in JAVA include (among others):

Type Meaning Range in JAVA


int integer about –2.15 x 109 to + 2.15 x 109
long large integer about –9.22 x 1018 to + 9.22 x 109
float real (decimal) numbers about –3.4 x 1038 to + 3.4 x 1038
double large decimal numbers about –1.80 x 10308 to +1.8 x 10308
char character Unicode set (includes ASCII)
boolean Boolean variables false, true

Variable names
Variable names can contain letters and digits, and (by convention) start with a lower case letter.
Some valid names are:

n, loopCounter3, myNumber1 etc.

When you declare a variable you tell the class what type it is and give it a name. This sets aside
memory space in which to store the variable.

Here are some examples of declaring one or more variables of different types. Note that you can
assign values to variables when you declare them. If you do not assign a value the variable is given a
default value.

int n, m, p = 15;
boolean isTooBig, isTooSmall, prime = true;
char character1, character2 = ‘k’;
double p, q = 3.5E25;
float x, y = 45.78 f; Note that the symbol “f” must follow a float initialisation.

A global declaration (immediately after the main class definition) means that all the “methods” of
the class can use these variables and their values. If it is not initialised (or “assigned” a value) a
global variable a default value. The default values are 0 for int and long, 0.0 for float and double and
false for boolean.

You can make local declarations in any block. This includes:


 Within a method.
 Within a for statement: eg for(int n=5; n < 10; n++);
 As a parameter to a method (more on this later).

If you only intend to use a particular variable within one method or one for loop, it is best to declare
it locally within that method or loop. This avoids cluttering up the main program. However, note
that:
 Locally declared variables must be initialised before using.
 If the same variable name is used both globally and locally, the local meaning takes
precedence within that block. We will look at this more when we discuss “methods”.
For example:

<import statements>
public class ScopeDemo extends Applet
{
int n, m; //global declaration of n and m
Number types
public void paint (Graphics g)
{ //g is a local parameter to paint()
int m, p; //local declaration of m, p
for (q = 1; q < 10; q++) //local declaration of q
p = m + 5; //the local version of m is used

Basic integer operations (types int and long)


 Assignment:
n = 4; //assigns the value 4 to variable n
 Sum:
sum = 4 + 7; //the variable sum is assigned the value 4 + 7
sum = n + 4; //variable sum becomes n + 4 where n is another integer variable.
 Difference
Diff = 7 – 3; //the variable diff is assigned the value 7-3.
 Product:
prod = n * 4; //variable prod is assigned the value n*4
 Integer division:
quot = n / 4; //eg 7/4 = 1; 13/4 = 3 etc
 Integer remainder or “modulus”:
rem = n%4; //eg 7%4 = 3; 13%4 = 1 etc
Some Java shortcuts
m += 3 same as m=m+3
m++ same as m=m+1
m -- same as m=m–1
m -= 3 same as m=m–3
m*=3 same as m = m*3
m /= 3 same as m = m/3 //integer or double division as appropriate
m %= 3 same as m = m%3 //still gives remainder for double division
Basic real operations (types float and double)
The operations on real numbers include assignment, sum, difference, product as for the integers. In
this case quotient is simply the normal decimal division. However note that all the standard
mathematical operations return a type double.
Precedence of Mathematical Operations (all types)
The order of precedence of standard mathematical operations is

() parentheses if more than one set of parentheses evaluated left to right


*/% if more than one operation, evaluated left to right
+- if more than one operation, evaluated left to right
Promoting
Java can only perform binary operations (such as + * - /) on two numbers of the same type. For
example, if you want to multiply an integer by a double, it will first promote the integer to a double
to give a double answer. For example 4 * 3.1 is converted to 4.0 * 3.1 to give a final answer of 12.4.

The order of promotion for numbers is: int  long  float  double.
Casting
There are some situations in which you want to convert one number type to another. You can do this
by using a cast such as (int), (double), (long) etc. For example
 (int) 45.6 is equal to 45
 (double) 33/7 converts 33 to a double, so that the result is 4.71…
 (double) (33/7) performs the integer division 33/7 which has result 4, and then converts this to
the double 4.0.
 (float) (2.2*3.3) converts the result of the operation 2.2*3.3 (which is double) to float.

Mathematics Methods
To obtain a full listing of standard mathematical methods that are available in all classes look at the
API help under java.lang.Math. The java.lang library is always loaded into an Applet so you do not
have to import the classes in this library in your programs.
Note that methods of the same name may be defined for different types (int, long, float, double).
Some of those used in the above class:
Math.round(float / double) rounds to the nearest integer
Math.sqrt(double) square root
Math.max(int, int) etc the maximum value of the two (for all types)
Math.random() a random double from 0 to 1.0
Writing the integer values to the applet window
The paint() method can use a line such as:

g.drawString("The sum is " + sum, 25, 50);

to write out the value of the variable. Note that to use drawString in this manner you must precede
the integer by a string.
If you do not wish to precede the number by text, you can either precede the number with a null
string “” in the drawString statement or use one of the methods which convert numbers to strings.
You will find these methods in the java API help under java.lang.Double, java.lang.Integer and so
on. Examples are:
g.drawString(“” + num, 25,60);
g.drawString(Double.toString(34.6), 25, 50);
g.drawString(Integer.toString(57), 25, 60);
g.drawstring(Long.toString(longNumber), 25, 60);

You might be wondering why these last few methods refer to, for example, “Integer” instead of int.
The reason is that there is a difference between objects of type Integer and variables of type int.
While the details of this are beyond this course, we will discuss this later on.

Controlling the number of decimal places in a printout


A decimal format is an object belonging to the DecimalFormat class of Java. To control the
formatting of a double in a printout you must:
1. Import the DecimalFormat class: import java.text.DecimalFormat;
2. Declare a DecimalFormat object DecimalFormat precision2;
3. Instantiate the DecimalFormat object in init(), setting the number of decimal places
(in this case, 2):precision2 = new DecimalFormat("#0.00");
4. Call the format method of DecimalFormat:
g.drawString("Rounded product is " + precision2.format(doubleNum), 25, 125);
Converting text (in a TextField) to numbers
If you wish to convert text from a text field into a number, the following methods are available, and
can be found in the API help for the appropriate class such as java.lang.Integer, java.lang.Double etc.
Note once again that “Integer”, “Double” etc are classes which form objects rather than variables.
More on this later!

intNumber = Integer.valueOf(input.getText()).intValue();
floatNumber = Float.valueOf(input.getText()).floatValue();
doubleNumber = Double.valueOf(input.getText()).doubleValue();

Integers have one further method which is a bit quicker:

IntNumber = Integer.parseInt(input.getText());

The boolean type


Boolean variables can be true or false. Boolean expressions are expressions that are either true or
false such as (4 < 5) or (23 == x). Some examples of assigning values to boolean variables are:

bool1 = false;
bool2 = 4 < 5; //the boolean expression (4 < 5) is true, so bool1 is true
bool3 = 4 < 5 && x < 23;

The standard comparison operators operate on numbers and some other simple variables to give a
boolean expression:

== equals
!= does not equal
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

The boolean operators operate on boolean expressions to give a result which is boolean.
 Logical AND is &&
 Logical OR is ||.
 NOT is !
 Exclusive OR is ^. (we won’t use this one in tests!)

Expressions are evaluated from left to right and stop evaluating as soon as the result is known. Eg if
((x == 45) && (y < 56)), when x is not equal to 45 the first expression is false so that the whole
expression will be false. Because of this, the second expression (y < 56) is not evaluated.

Note that Java also provides versions of AND & and OR | which allow the program to evaluate the
whole of a long expression. Programs using these will run more slowly and may have some
unexpected results in some cases.
Order of precedence including comparison operators

() brackets
++ -- (<type>) ! unary increment and decrement, cast: also includes unary + and -
*/% product, quotient and modulus
+- binary addition and subtraction
< <= > >= comparison operators
== != test of equality or inequality
&& logical AND
|| logical OR
= += -= *= /= %= assignment operators

In each case, operations of a similar precedence are evaluated from left to right.

The character type char


Characters include letters, digits, symbols, punctuation marks and various control characters such as
tab, new line etc.
Java uses the Unicode character set which uses 16 bits to store a large number of symbols. Unicode
includes the older ASCII 8 bit character set.

Declaring a character:

eg char digit1, digit2 = ‘k’;

Operations on characters
The basic comparison operators apply to characters, and compare their numeric values in Unicode.
For example in the ASCII and Unicode character sets, ‘a’ has numeric value 97 and ‘A’ has value 65,
so that
‘a’ > ‘A’.

Characters and strings


Strings, which are enclosed in “” punctuation marks, contain one or more text characters. There are
a number of methods which relate characters to strings and we will deal with these when discussing
strings.

To print a character to screen you can use methods similar to those used with numbers. For example:

g.drawString(“The character is” + digit1, 20, 40);


g.drawString(Character.toString(digit1), 20, 40);

When you type into a TextField, you generate an object of type String. If you want to actually read in
variables of type char you can convert the (first letter of) the String to a character using the String
method charAt(<position of character in string>). The first position in a string of characters is
numbered zero (0).

For example, to get a character char1 from a TextField charInput you would write:

char1 = charInput.getText().charAt(0);

Character methods
As with Double, Integer and so on, Character objects are part of the java.lang package and have a
number of useful methods. While you should look these up in the Java API help, some of the useful
Character methods (applied to a variable char1 of type char) include:
Methods with a Boolean output:
Character.isDigit (char1)
Character.isLetter (char1)
Character.isLowerCase (char1)
Character.isUpperCase (char1)
Character.isLetterOrDigit(char1)
Character.isSpace (char1)
Character.isWhiteSpace (char1) //”white spaces” include space, tab, new line

Methods to modify a character.


char2 = Character.toUpperCase (char1); //Converts lower case letter to upper case
char2 = Character.toLowerCase (char1);
Theoretical Exercise 14

1. Classify the following variable names as valid, unconventional or invalid:


(a) bool_var (b) boolVar (c) BoolVar (d) boolVar1 (e) 2boolVar

2. What is the range of possible values for the following variables?


rand1 = Math.random()
rand2 = Math.random() * 100
rand3 = (int) Math.random() * 100
rand4 = (int) (Math.random() * 100)
rand5 = (int) (Math.random() * 100 + 1)

3. If p = 4, q = 6 and r = 8, what is the value of the following expressions. Indicate any syntax
errors.

(p < 10) && (q > 6)


p < 10 && q++ > 6
(p > 2) || q = 7
(p > 2) || r == 10
(p > 2) && (q > 10) || (r = 8)
(p > 2) || (q > 10) && (r = 8)

4. Write out Java type statements which are true under the following conditions:
x lies between 10 and 20
x does not lie between 10 and 20.

5. If ch1 = ‘a’, ch2 = ‘A’ and ch3 ‘ ‘ (space) what is the value of the following expressions:

ch1 < ch2


ch2 <= ‘B’
Character.isUpperCase(ch1);
Character.isUpperCase(ch2);
Character.isSpace(ch1);
Character.isSpace(ch3);
Character.isLetterOrDigit(ch3);
Exercise 15 Methods

Methods have a number of important uses:


 They enable you to break up a class into “modules” which each perform a distinct task. Classes
written in this way are much easier to implement and to follow.
 They enable the code for a repetitive task to be written once, and used many times in a class.
 In an object oriented language, they provide the means of using the information that is stored in
an object. They also enable you to use the features of one class in another (such as when you call
Math.random().

The standard Applet methods


We have already made use of a number of the key methods of the Applet Class. When an Applet is
run this is what happens:
 A window is opened for it
 3 methods are run automatically in order. If we don't further define these we get an empty version
by default: in this case, they do not have to be written in your class code – they run automatically
anyway.
 init() : init is used to set up the GUI (Graphical User Interface) by instantiating and adding
components, define the initial values of variables, tell actionPerformed() which events to
listen to and set up sounds and images to be used by the Applet.
 start() We will never use this method in this course. However, it can be modified for more
advanced purposes.
 paint(): This is used to display graphics objects. More on this below!

Once the user finishes with the Applet two more key methods are called. These methods can be
modified by the programmer for more advanced purposes, but we will never do this in this course.
The methods are
 stop() which basically stops the Applet running and
 destroy() which removes all features of the Applet from memory.

Other standard methods that you have used are the various event handling methods. How to use these
is described in the notes on events. They include:
 public void actionPerformed(ActionEvent e) {}
 public void mousePressed (MouseEvent e) {}
 public void mouseClicked (MouseEvent e) {}
 public void mouseReleased(MouseEvent e) {}
 public void mouseEntered (MouseEvent e) {}
 public void mouseExited (MouseEvent e) {}
 public void mouseDragged (MouseEvent e) {}
 public void mouseMoved (MouseEvent e) {}.

More on paint()
The paint() method is executed
 Once, immediately after init/start.
 Whenever the applet window is redrawn, for example when you change windows.
 When called from actionPerformed (which doesn’t have access to graphics) using repaint().

repaint()
 clears applet windows of graphics (but not the GUI components which sit on top of the output
window).
 calls paint.
What do you code in paint() and in the various event methods?
Some rules of thumb are:
 If it uses the Graphics object g it can only be executed in paint.
However, note that g can be used in other methods which are called in paint() – see later.
 If it uses the Event object e it can only be executed in actionPerformed.
However, note that e can be used in other methods which are called in actionPerformed and the
other event handling methods – see later.
 Other statements might be in either method. Try to carry out calculations etc in actionPerformed
unless this requires a lot of information being passed to paint.
 If there is a lot of work to do in either paint() or actionPerformed(), you would normally split it
up into smaller methods. This is described in the next section.
Exercise 16 Writing your own methods
Methods with no input or output
In the following example, “Hello()” is a method which has no input and which does not change any
object or variable in the class so that it can be regarded as having no output. Note that the parameter
brackets () are necessary to indicate that it is a method.

The word void will make more sense later: it means that the method does not generate a new value.

Whenever you want to use a method you call or invoke it from another method such as paint().

import java.applet.Applet;
import java.awt.*;

public class Method1 extends Applet


{
//The definition of the method Hello()
public void Hello()
{
showStatus("Hello and what a nice day it is.");
}
public void paint (Graphics g)
{
Hello(); //Method “call”
}
}

Method with an input or parameter but no output to the class


In this case we supply data to the method as a parameter. If we want to use parameters we must:
 Declare the parameter in the method definition. In the example below the method has a parameter
of type string.
 Give the method a value in the method call. In the example below the value of the parameter is
“Hello. It is still a nice day.”

import java.applet.Applet;
import java.awt.*;

public class Method2 extends Applet


{

//The definition of the method Hello(String)


public void Hello(String s)
{
showStatus(s);
}
public void paint(Graphics g)
{
Hello("Hello. It is still a nice day."); //Method call includes parameter value
}
}
Method with input parameter and output to an object in the class
In the next example, the method alters the properties of an object (in this case a text field) within the
class. The method itself does not change the data.

import java.applet.Applet;
import java.awt.*;

public class Method3 extends Applet


{
TextField t;

public void init()


{
t = new TextField(20);
add (t);
}
public void Hello(String s)
{
t.setText(s); //Changing the data of object t
}

public void paint(Graphics g)


{
Hello("Hello. It is still a nice day.");
}
}

Method with input parameter and output which changes the input value
In this example, the method alters both the properties of an object within the class and also modifies
the data within supplied to it in the parameter.

import java.applet.Applet;
import java.awt.*;

public class Method4 extends Applet


{

TextField t;

public void init()


{
t = new TextField(30);
add (t);
}

public void Hello(String s)


{
t.setText(s + " Good luck");
}

public void paint(Graphics g)


{
Hello("Hello. It is still a nice day.");
}
}
Another example of the above
This example has an int parameter.

import java.applet.Applet;
import java.awt.*;

public class Method4b extends Applet {


TextField t;

public void init()


{
t = new TextField(10);
add (t);
}

public void square(int i)


{
t.setText(Integer.toString(i*i));
}

public void paint(Graphics g)


{
g.drawString(square(9), 20, 40);
}
}

Method which has no input but generates or “returns” a new value


In the following example the word “void” has been replaced by “int”. This tells the class that the
method generates a new value of type int. When the method is called it acts as a new value in the
class.

The word return specifies the value that the method generates.

import java.applet.Applet;
import java.awt.*;

public class Method5 extends Applet {

public int rand()


{
int x = (int)(1 + Math.random()*10);
return x;
}

public void paint(Graphics g)


{
g.drawString("A random integer between 1 and 10 = " + rand(), 25, 50);
}
}
Method which has an input and generates a new value
This method has an input parameter and generates a new value. It acts as a typical mathematical
function such as sin(x) which generates a new value from an input parameter. When this method is
called, it acts in the same way as another value in an expression.

import java.applet.Applet;
import java.awt.*;

//This method extends the previous method to choose a


//random number between bounds that can be varied.

public class Method5b extends Applet


{
int upper = 25;

public int rand(int max)


{
int x = (int)(1 + Math.random()*max);
return x;

public void paint(Graphics g)


{
g.drawString("A random integer between 1 and " + upper +" = "
+ rand(upper), 25, 50);
}
}

The next example is similar:

import java.applet.Applet;
import java.awt.*;

public class Method6 extends Applet


{

public int square(int i)


{
return i*i;
}

public void paint(Graphics g)


{
g.drawString("The square of " + 9 + " = " +(square(9)), 25, 50);
}
}
A summary of the theory of methods in Java

The general form of a method definition is as follows. The first line is called the heading.

Nearly all methods that The type or class that the Use normal Java If no formal parameters
you will use start with method returns (int, identifier rules. use ().
the word “public”. Other TextField etc). If the Begin with lower More than one formal
words are “private” and method does not return a case letter. parameter separated by
“protected”. value use the word void. comma.

public return_value_type method_name ( formal parameters ) {


declarations; //These are local variables or objects.
statements;
return <expression>; //If required. Must be included if the method is not
void.
}

The method call


Identifying where the method definition can be found
To use a method you call or invoke it from another method. The method call must be clear about the
class in which the method is defined.

 If the method was defined in the same class in which it is called, you simply call it using the
name of the method. init(), paint(), start(), destroy() and stop() are automatically defined in each
new class and so can be called directly by name in this way. Any method that you write in a class
(such as in the simple examples above) is also called in this way.

 If the method is defined in another class (such as most of the standard Java methods that you will
use), you must identify the class which defines the method. There are three different ways of
doing this, and which one is appropriate depends on how the method was originally defined. (See
discussion of “instance” and “static” methods in the next section.)

 variable.name(actual parameters) textFieldName.setText(“Hello”);


 name (actual parameters) showStatus(“Hello”);
 class.name (actual parameters) Math.max(23, 45);

How to place a method call in the class


If the method has been declared as void the call to the method forms a separate statement. For
example,
square(9); //from the above examples
Hello("Hello. It is still a nice day."); //also from the above examples
g.drawString(“Hello”, 25, 25);

If the method is other than void, it returns a new value which is used in an expression just like any
other value. For example:
g.drawString("The square of " + 9 + " = " +(square(9)), 25, 50); //from above
examples
y = Math.max(23, 45);
Return Return has two uses:

1. To cause the current method to end. In the following example if b == -1 the method exits without
printing out the value of b.

public void paint (Graphics g)


{
g.drawString ("The value of a is " + a, 25, 50);
if (b == -1) return;
g.drawString ("The value of b is " + b, 25, 75);
}

2. To specify a value to be returned to the caller.

public int rand(int max)


{
int x = (int)(1 + Math.random()*max);
return x;
}

There are two ways in which you can use the value returned by a method:
 You might use the new object or datatype (for example to print it) and then discard it from
memory. As an example, to print out the value of an integer you might use:
g.drawString(Integer.toString(456), 25, 50);

 If you want to keep the new object or primitive type in memory you must have declared it. As
an example, you can keep the string value of an integer if you write:
string1 = Integer.toString(456);

Examples of methods that do not have a return include many of the graphics methods such as
SetColor, drawRect, drawString.
Scope Rules
A block is any section of a class enclosed in { } brackets. Blocks can include:
 A class (application or applet)
 A method.
 A section of a for loop or a conditional statement etc.

Variables can be defined in four ways:


1. Instance variables: These are defined immediately after the class heading and have global
scope: that is, they can be used anywhere in the class. Any variables that are used in more than
one method should be made instance variables: in this way the value of the variable can be
transferred from one method (such as init()) to another (such as paint()). As an example:
public class Method5b extends Applet {
int upper = 25; //upper is an instance or global variable

2. After a method heading: These are variables that have a scope that is local to the method: they
are not defined outside the method. Any variables that are used only in the method should be
made local. As an example:
public int rand(int max)
{ //max is a formal parameter
int x = (int)(1 + Math.random()*max); //x is a local variable
return x;
}
3. In the method heading (parameters): These formal parameters are only defined within the
method – that is they are local variables in the method. However, they provide a link to the
actual parameters used in the class. In the above example max is a formal parameter local to the
rand method.

4. Variables defined in blocks (such as for loops): These are only defined within that block. An
examples is:
for (int i; i < 10; i++)

If two variables have the same name:


 If they are local to different blocks they are completely independent.
 If once is local or block and the other is global (instance), the identifier stands for the local or
block variable. We say that the local variable “hides” the instance variable.

Parameters
Formal and Actual parameters
 The formal parameters are the identifiers used in the definition of the method.
 The actual parameters are the values used in the method call. These might be literal values or
instance variables that have been given a value.

In a method call the actual parameters must exactly match the formal parameters in number and in
type. The only exception to this is if the type of one of the actual parameters can be promoted to the
type of the formal parameter. We say that the actual parameters are passed to the formal parameters.

The following example shows a method definition heading, and how this method might be called
from another method:

//Method definition
public double methodExample(int a, int b, double x, boolean t)
{
statements;
}

//Method call (in another method such as paint() or a method made up by the programmer etc)
//In the following examples, val1 and val2 are both int variables, doub1 is a double and b is a //boolean. All of
these variables must have a value before the method is called.

d1 = methodExample (2, val1, 23.56, true);


d2 = methodExample (val2, 4, doub1, b);

Call-By-Value and Call-By-Reference


 Predefined types (int, float etc) are passed “Call-By-Value”: a copy of the actual parameter is
passed to the formal parameter, without in any way changing the value of the original actual
parameter.

 Class variables (TextField, Button, Label …) are passed “Call-By-Reference”: the original object
is referred to and its values may be changed by the method. We say that the formal parameter is
an alias for the actual parameter (another name for the same object).

The following class is a simple example of this. The method tryToChange has an int and a TextField
parameter. It sets new values for each of these parameters. When it is called, the int value is not
changed outside the method, while the TextField value is changed.
import java.applet.Applet;
import java.awt.*;

public class ParameterDemo extends Applet


{
int i;
String s1 = "Hello ",
s2 = "Goodbye ";
TextField t;

public void init()


{
i = 12;
t = new TextField(s1);
add (t);
}

public void tryToChange(int j, TextField f)


{
//”attempts” to set the int to 12 and the textfield to “Goodbye”
j = 24;
f.setText(s2);
}

public void paint (Graphics g)


{
g.drawString("Original value of int is " + i, 25, 100); //output 12
g.drawString("Original value of text is " + t.getText(), 25, 125);//output Hello
tryToChange(i, t);
g.drawString("Value of int after tryToChange is " + i, 25, 150);//output 12
g.drawString("Value after tryToChange is " + t.getText(), 25, 175); //output Goodbye.
}
}

Method Overloading
Sometimes we want to be able to do similar things to different types or objects. In this case, Java
enables methods that are different (because their parameters are different) to have the same name.
There are many examples of this, and a very small selection is:
 toString(<type>): the type can be int, double, and many more (including both types and objects).
 Math.max(<type, type>): the types can be (both) int, double etc

The following example shows how a new method max can be defined to give the maximum value of
3 integers or 4 integers or three doubles. Which version of max is called depends on the number and
the type of parameters in the call.

public int max(int p, int q, int r)


{
//first version of max
return(Math.max(Math.max(p, q),r));
}

public int max(int p, int q, int r, int s)


{
//second version of max
return(Math.max(Math.max(Math.max(p,q),r),s));
}

public double max(double x, double y, double z)


{
//third version of max
return(Math.max(Math.max(x,y),z));
}

public void paint (Graphics g)


{
g.drawString ("Maximum of three integers is " + max (12, 24, 36), //call first version
25, 50);
g.drawString ("Maximum of four integers is " + max(12, 13, 6, 9), //call second version
25, 75);
g.drawString ("Maximum of three doubles is " + max(1.56, 2.78, 1.76), //call third version
25, 100);
g.drawString ("Maximum of three doubles is " + max(5, 2.78, 1.76), //promote 5 to 5.0
25, 125);

Modularising Graphics
Often it is convenient to break up a graphics method into smaller methods, particularly if there are
repetitive tasks to undertake.

The following class shows how this can be done. A menu is located in a menu method, while the
method thickline enables repeated drawing of a thick line. Note that the Graphics objects in the
various methods can be given a formal parameter which is any valid identifier.

import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet


{

public void menu(Graphics g, String s1, String s2, String s3)


{
g.drawString(s1, 120, 150);
g.drawString(s2, 120, 175);
g.drawString(s3, 120, 200);
}

public void thickLine(Graphics graph, int x1, int y1, int x2, int y2, int thickness)
{
for (int i = 0; i <= thickness; i++)
graph.drawLine(x1+i, y1, x2+i, y2);
}

public void paint(Graphics g)


{
menu(g, "Menu item 1", "Menu item 2", "Menu item 3");
thickLine(g, 150, 10, 250, 150, 10);
thickLine(g, 150, 10, 50, 150, 10);
thickLine(g, 50, 150, 150, 290, 10);
thickLine(g, 250, 150, 150, 290, 10);
}
}
More advanced topics, including notes on using the JWS API help:
The terms used in these notes are not examinable, but knowing about them will help you to make
sense of the JWS help.

Public private and protected methods


 public: the method can be used by any other method. These are the methods that provide a java
program with the means of operating on an object.
 private: the method can only be used by other methods in the same class. These are methods that
are only used within a class to do a particular job that the main java program does not need to
know about.
 protected: the method can only be used by other methods in the same class or in a subclass of
this class.

Instance and Static methods


Instance methods: Methods preceded by the variable name (when called outside the class in which
they are defined) are called Instance Methods (RED dot in the JWS API help). The method operates
on an object in that class. For example:

Example Class Declarations


string2 = string1.trim(); String String string1, string2;
len = string1.length(); String int len; String string1;
string1 = value1.getText(); TextComponent TextField value1;
myButton.addActionListener(this); Button Button myButton
string1 = num.toString(); Integer int num; String string1;

Static methods: Methods preceded by the class name (when called outside the class in which they
are defined) are called Static Methods (GREEN dot in the JWS API help). They operate on the
class as a whole. For example:

s1 = Integer.toString(num) Integer String s1; int num;


num = Integer.parseInt(s1); Integer String s1; int num;
num = Math.round(real); Math int num; double real;
big = Math.max(num1, num2); Math int big, num1, num2;
string1 = Integer.toString(num); Integer int num; String string1;

Sometimes the same name can be given to two different methods one of which is static and the other
an instance method. The toString methods provide an example.

Instance and Static variables


Instance variables: (PURPLE in JWS help). Examples are Font.size and Font.name. They are the
variables that store the data in an object, and are the ones that you define when you declare the global
variables in a class using a statement such as:

int num1, num2;

Static variables: (BLUE in JWS help) Examples are Math.PI and Math.E, or Color.red and
Color.blue. These are essentially constants that apply to every object in the class. A variable is made
“static” by including the word static at the beginning of it’s declaration. For example:

static int constant1, constant2;


Wrapping
Sometimes when looking at what is returned by a method, you must be aware of the distinction
between an object (such as an Integer) and the data stored by the object which will be a primitive
type (such as an int). When this happens the object is said to “wrap” the type.

Consider the following line:

int2 = Integer.valueOf(s2).intValue();

Why are there two apparent attempts at getting the integer value of the string s2?

If you look up valueOf in the Integer class you will see that it returns an Integer Object. This integer
object contains the integer as its data, but it also contains other information: it is not the same as the
primitive data type int. To get the actual value we have to add on the method intValue() which
applies to an Integer Object and returns a primitive type int which corresponds to the data of the
Integer object.

In this case we say that the Object Integer “wraps” the data type int.

Methods and Constructors


All classes contain methods, which are the means by which the class manipulates the class data

Constructors: (YELLOW dot in JWS help). A constructor is a special kind of method which is
called when an object is created. It is used to give an initial value to the data stored in the object. For
example, if you use the code:

s1 = new String(“Hello”);

you are actually calling one of the String constructors. You will not be required to write constructors,
but you should understand their use in the Java help.

Classes and Interfaces:


Classes are the major components of a Java program and are used to create objects. The class will
contain data (the instance variables) and methods to operate on this data. A complete Java program
will often contain a number of different classes linked in some way by the methods and the instance
variables.

Interfaces are similar in many ways to classes. The differences are beyond the scope of this course.
Programming exercises 16
1. Areas
Here are the formulae for the areas of a number of different shapes in terms of their basic dimension
(radius, side length etc).

Square: area = (side length)2

Circle: area = PI* radius2

Hexagon: area = 1.5*3 * r2

Equilateral triangle: area = 0.25 *3 * r2

Write four procedures which:


 take the main dimension as an input parameter
 return the area of the corresponding shape.

Now write a program which will:


 allow the user to select one of the four shapes,
 allow the user to input the main dimension of the shape,
 print out the area of the shape.

Your program should call the above procedures as appropriate from the actionPerformed() method,
and as always print out the area from the paint() method.

Techniques for getting the choice of shape from the user:


 A menu (Label) lists letters or numbers corresponding to each shape. The user types in the
appropriate letter or number in a TextField. This is simple to program, but not simple for the
user.
 Buttons are used to select the shape, and the getSource() method is used to determine which
button has been pressed. This involves a bit more programming but is much better for the
user.
 There are many more components which enable to user to choose one of a number of
different options. One of the simplest to program is the List which uses actionPerformed to
indicate which item on the list has been chosen by the user.

2. Write Graphics methods to draw:

 horizontal and vertical dashed lines. These two methods should include parameters for
 the graphics object g
 the starting coordinates of the line
 the length of the line in pixels
 the length of the dashes in pixels.

 horizontal and vertical thick lines. These two methods should include parameters for
 the graphics object g
 the starting coordinates of the line
 the length of the line in pixels
 the width of the line in pixels.

 rectangles and ovals with thick sides. These two methods should include parameters for
 the graphics object g
 the top left coordinates
 the width
 the the height
 the thickness of the sides in pixels

Using these methods and if necessary other methods (such as thick or dashed lines inclined at 45)
draw up a nice picture on the screen. Add colors to your picture. The picture could be:

 a nice house and garden


 a plan for a computer game – perhaps a maze with various obstacles etc
 etc etc

3. Assignment Rock, paper, scissors

This is an assignment due before the end of May. The completed code should be emailed to
your teacher with the subject “RPS”.

ALL WORK SHOULD BE YOUR OWN – IF THERE IS EVIDENCE OF COPYING, THE


MARKS WILL BE SHARED BETWEEN THOSE WHO HAVE COPIED.

There will be a penalty for late submission of the assignment.

Marks will be based on:


 Does it work correctly.
 How well structured the program is (including the use of methods with appropriate
parameters).
 How entertaining it is – this will involve the use of pictures, sounds etc.

In the game rock, paper, scissors the two players each choose one of the three. The winner is then
decided by the rules:
 Paper covers rock, paper wins.
 Scissors cut paper, scissor wins.
 Rock breaks scissors, rock wins.
 All matching combinations are ties.

Write a program to simulate the game, with the user playing the computer. As well as paint() and
actionEvent, your program should include procedures for:
 Allowing the computer to make a choice of rock, paper or scissors. This will involve a
procedure which has no parameters, but which returns a value (perhaps int or char) which
corresponds to rock, paper or scissors.
 Allowing the user to make a choice of rock, paper or scissors. The use of buttons or a list
would be most appropriate. The method returns a value which corresponds to rock, paper or
scissors similar to that produced by the previous method.
 Deciding the winner in each round of the game and tallying up the total score (wins, ties and
losses).

An interesting version of the game will have appropriate images and sounds, including a suitable
reward if the user wins.
Introductory exercises in Methods

1. Answer the questions for the class given:

(a) What is the output? public class squares extends Applet {


(b) What is the formal parameter in the int m = 5;
method? public int square(int value) {
return value*value;}
(c) What is the global variable in the
public void paint (Graphics g) {
class? g.drawString("" + square(4), 20, 40);
(d) What is the actual parameter in the g.drawString("" + square(m + 4), 20, 60);
procedure call? }
}

2. Answer the questions for the class given:

(a) What is the output? public class fact1 extends Applet {


(b) How would you declare a more public int fact6() {
general method which calculated the return 6*5*4*3*2;}
public int fact8() {
factorial of any integer n. return 8*7*6*5*4*3*2;}
public void paint (Graphics g) {
g.drawString(""+fact8()/fact6(), 20, 40);
}
}

3. Answer the questions for the class given, which is a variation of the previous class:

(a) What is the output? public class fact2 extends Applet {


(b) Could you reverse the order in public int fact6() {
which the two methods are defined? return 6*5*4*3*2;}
public int fact8() {
return 8*7*fact6();}
public void paint (Graphics g) {
g.drawString(""+fact8()/fact6(), 20, 40);
}
}

4. Here are two classes which do the same job:

import java.applet.Applet; import java.applet.Applet;


import java.awt.*; import java.awt.*;
public class cube1 extends Applet { public class cube2 extends Applet {
int m = 4; int m = 4;
public int cube(){ public int cube(int n){
return m*m*m;} return n*n*n;}
public void paint (Graphics g) { public void paint (Graphics g) {
g.drawString(""+cube(), 20, 40); g.drawString(""+cube(m), 20, 40);
} }
} }

(a) What is the output of each class?


(b) Which class defines a method with a parameter?
(c) In class cube2, what is the formal parameter and what is the actual parameter when the method
cube(int) is called?
(d) Which of the two classes is the more modular?
5. Here are two more classes which do the same job.
import java.applet.Applet; import java.applet.Applet;
import java.awt.*; import java.awt.*;
public class hello1 extends Applet { public class hello2 extends Applet {
String s1 = "Hello"; String s1 = "Hello";
public void newString(String s2){ public String newString(String s2){
s1 = s1 + s2;} return s1 + s2;}
public void paint (Graphics g) { public void paint (Graphics g) {
newString(" to you"); g.drawString(newString(" to you"),
g.drawString(s1, 20, 40); 20, 40);
} }
} }

(a) What is the output of each class?


(b) What is the value of the String s1 when each of the classes is completed. What programming
lines could you add to check this?

6. Here are some programs which look similar. What is the output of each? Explain.
import java.applet.Applet; import java.applet.Applet;
import java.awt.*; import java.awt.*;
public class int1 extends Applet { public class int2 extends Applet {
int a, b, c; int a, b, c;
public void intMethod (int p, int q, public void intMethod () {
int r) { a = 2;
p = 2; b = 3;
q = 3; c = 4;}
r = 4;} public void paint (Graphics g) {
public void paint (Graphics g) { intMethod();
intMethod(a,b,c); g.drawString("" + a, 20, 40);
g.drawString("" + a, 20, 40); g.drawString("" + b, 20, 60);
g.drawString("" + b, 20, 60); g.drawString("" + c, 20, 80);
g.drawString("" + c, 20, 80); }
} }
}
(Answers: int1: 0, 0, 0; int2: 2, 3, 4;)

7. Here is another variation on the same theme as question 6.


import java.applet.Applet; import java.applet.Applet;
import java.awt.*; import java.awt.*;
public class text1 extends Applet { public class text2 extends Applet {
TextField a, b; TextField a, b;
public void init (){ public void init (){
a = new TextField(10); a = new TextField(10);
b = new TextField(10); b = new TextField(10);
add(a); add(a);
add(b); add(b);
} }
public void intMethod (TextField s1, public void intMethod () {
TextField s2) { a.setText("2");
s1.setText("2"); b.setText("3");}
s2.setText("3");} public void paint (Graphics g) {
public void paint (Graphics g) { intMethod();
intMethod(a, b); }
} }
}
(a) What is printed in the two TextFields when each class is run? (Ans: 2, 3 in each case)
(b) What is the difference between the classes in questions 6 and 7?
8. And here is yet one more variation on the theme of questions 6 and 7.
import java.applet.Applet; import java.applet.Applet;
import java.awt.*; import java.awt.*;
public class string1 extends Applet { public class string2 extends Applet {
String a, b; String a, b;
public void stringMethod (String s1, String s2) public void stringMethod () {
{ a = "2";
s1 = "2"; b = "3";}
s2 = "3";} public void paint (Graphics g) {
public void paint (Graphics g) { stringMethod();
stringMethod(a, b); g.drawString(a, 20, 40);
g.drawString(""+ a, 20, 40); g.drawString(b, 20, 60);
g.drawString(""+ b, 20, 60); }
} }
}
(a) What is the output of each class? (Ans string1 null, null; string2 “2”, “3”)
(b) What are the similarities between this program and the preceding two programs?
(c) Why was it necessary to add the null string “” in the drawString methods of string1?
9. This is a totally ridiculous bit of programming, but what is its output anyway?
import java.applet.Applet;
import java.awt.*;
public class junk extends Applet
{
int a = 6, b = 7, c = 8;
public int stringMethod (int q, int r)
{
a = r;
r = q;
return r;
}
public void paint (Graphics g)
{
g.drawString (""+ stringMethod(3, c), 20, 20);
g.drawString(""+ a, 20, 40);
g.drawString(""+ b, 20, 60);
g.drawString(""+ c, 20, 80);
}
} (Answer: 3, 8, 7, 8)
10. What is the output of the previous program is the parameters are changed to (c, b) and (c,c)?
(Answer: 8, 7, 7, 8 and 8, 8, 7, 8)
11. Find the mistakes in the next program (there are at least 4 mistakes):
import java.applet.Applet;
import java.awt.*;

public class junk2 extends Applet {


int a, b, c;
public int intMethod (int q, r) {
a = r;
r = q;}
public void paint (Graphics g) {
intMethod(c, c);
g.drawString(""+ a, 20, 40);
g.drawString(""+ q, 20, 60);
g.drawString(""+ intMethod(), 20, 80);
}
}
Exercise 17 Mouse events and events due to other components Events
You have had an introduction to events in Introductory Exercise 6, and you have used events with
TextFields and Buttons in many of the later exercises. You have used the getSource() method to
determine which Applet component triggered an event in Introductory Exercise 12. Here is a repeat
of the basic theory:

An event is an action performed by the user which gives information to the class. GUI components
are often used to generate events. Events can include things such as
 Clicking a Button or one of the other components such as a List, CheckBox etc.
 Pressing <return> with the mouse cursor in a Text Field.
 Clicking or moving a mouse.

The ActionListener interface


If we want the class to “listen” to events, such as the press of a button called addButton, we have to

1. Tell the class to implement ActionListener:


public class <ClassName> extends Applet implements ActionListener {

2. Tell the class which events to listen to (there might be a number of possible events):
addButton.addActionListener(this);

In this case, we are telling the class to listen to the GUI component that we have named
“addButton”. The word this tells the class that “this” class is doing the listening (it is possible to
listen to events in other classes).

4. Use the actionPerformed method to respond to the event:


public void actionPerformed(ActionEvent e)

How do you decide which component generated an event?


If a class is listening to events generated by a number of different Applet components, you must be
able to tell which component generated the event. There are two ways of doing this, both of which
use the getSource() method.

1. To tell which specific component generated the event, you name components in code such as
the following:

if (e.getSource() == jimButton) jim ++;


if (e.getSource() == valueText)
value = Integer.valueOf (valueText.getText()).intValue();

An example of the use of this were the voting and calculator programs of Introductory Exercise 12.

2. To tell what type of component (TextField, Button etc) generated an event, you can use the
instanceOf comparison operator as in the following example:

if (e.getSource() instanceof TextField) <statement>;

Other interfaces
As well as ActionEvent there are many other “interfaces” which control the response of the applet to
the events generated by various types of components or by the mouse or keyboard. Some of these are
considered (in a very introductory way) in the remainder of these notes.
Some other components that generate Events
So far you have used Button and Text Field objects to generate action events. There are many other
components which will also generate events and while you will not be examined on all of these, you
should become familiar with how to use them in your own programs.
The following pages give examples of programming some of these components, without further
explanation. You can copy these into Java Workshop in order to try them out. You should be able to
write similar programs yourself.
Lists (use ActionEvent interface)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/* A simple demonstration of the List component. The user clicks on a list of colours, which sets
the background color. */
public class ListDemo extends Applet implements ActionListener
{
List colorList; //declare a list
Label prompt;

public void init()


{
//instantiate and add the prompt
prompt = new Label("Double click the list to set the color.");
add(prompt);

//Create a list of 5 items. Do not allow multiple selections


colorList = new List (5, false);

//Program will listen to this list


colorList.addActionListener (this);

//Add items to list (these must be strings)


colorList.add("Red");
colorList.add("Blue");
colorList.add("Green");
colorList.add("Yellow");
colorList.add("Cyan");
//Add list to applet
add (colorList);
}

public void actionPerformed (ActionEvent e)


{
//Respond to list item that has been double clicked.
//List items are numbered from 0 upwards.

switch (colorList.getSelectedIndex())
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue); break;
case 2: setBackground(Color.green);break;
case 3: setBackground(Color.yellow); break;
case 4: setBackground(Color.cyan);
}
repaint()
}
}
Checkboxes (use ItemListener interface)
A checkbox allows the user to choose between two options one of which is “true” and the other
“false”. In the following example the choices are milk / no milk, sugar / no sugar, strong / not strong.
Code that you have not used before is in bold.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/* A class to demonstrate Checkboxes. The user uses the Checkbox to determine how he likes
his coffee. Checkboxes use the ItemListener interface. */

public class CheckDemo extends Applet implements ItemListener


{
Checkbox milk, sugar, strong; //declare three Checkboxes
String order = "";

public void init()


{
//instantiate Checkboxes
milk = new Checkbox ("Milk?");
sugar = new Checkbox ("Sugar?");
strong = new Checkbox ("Strong?");

//add Checkboxes to window


add (milk);
add (sugar);
add (strong);

//listen to Checkboxes in itemStateChanged


milk.addItemListener(this);
sugar.addItemListener(this);
strong.addItemListener(this);
}

public void paint (Graphics g)


{
g.drawString (order, 20, 60);
}

//method itemStateChanged must be used with the ItemListener interface


public void itemStateChanged (ItemEvent e)
{
order = "I like ";

//In each case the getState method is TRUE if the Checkbox has been
//ticked and FALSE otherwise.
if (strong.getState())
order = order + "strong coffee ";
else order = order + "weak coffee ";
if (milk.getState())
order = order + " with milk";
else order = order + " no milk";
if (sugar.getState())
order = order + " and with sugar";
else order = order + " and no sugar";

repaint();
}
Radio Buttons (use ItemListener interface)
Radio buttons are a variation of the Checkbox: however, only one radio button can be ticked as true
at any time.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/* Radio buttons are similar to Checkboxes except that only one


button can be true at any one time. That is, only one choice is
allowed. They are set up and used as are ordinary Checkboxes
except that they are controlled by a class CheckboxGroup.*/

public class RadioDemo extends Applet implements ItemListener{

CheckboxGroup votes;
Checkbox jim, joe, sue, sal;
String winner;

public void init ()


{
//Instantiate the controlling CheckboxGroup
votes = new CheckboxGroup ();

//Each Checkbox has a second parameter linking it to the CheckboxGroup.


//There is also a third parameter indicating the initial state of the Checkbox (ticked or
//not. If more than one is marked true, the last of these is ticked.
jim = new Checkbox ("Jim", votes, false);
joe = new Checkbox ("Joe", votes, false);
sue = new Checkbox ("Sue", votes, false);
sal = new Checkbox ("Sal", votes, false);

//add each Checkbox to the window as normal


add(jim);
add(joe);
add(sue);
add(sal);

//Listen to each Checkbox in itemStateChanged


jim.addItemListener(this);
joe.addItemListener(this);
sue.addItemListener(this);
sal.addItemListener(this);

public void paint (Graphics g)


{
g.drawString("The winner is " + winner, 20, 80);
}

public void itemStateChanged (ItemEvent e)


{
if (e.getSource () == jim) winner = "Jim";
else if (e.getSource () == joe) winner = "Joe";
else if (e.getSource () == sue) winner = "Sue";
else if (e.getSource () == sal) winner = "Sal";
repaint();
}
}
Scroll bars (uses AdjustmentListener interface)
Scroll bars allow you to adjust the values of integer variables by moving a “scroll box” along a Scrollbar or by using the
Scroll arrows at each end of the Scrollbar. Here is a fairly complex example involving two Scrollbars controlling the
width and height of an oval drawn on the screen.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class ScrollDemo extends Applet implements AdjustmentListener


{
Scrollbar scrollHeight, scrollWidth;
int height, width; //Height and width of oval drawn on screen

public void init ()


{
height = width = 200; //Initial values
scrollHeight = new Scrollbar (Scrollbar. //Instantiate Scrollbar
VERTICAL, // Scrollbar in vertical direction
200, // Initial value of Scrollbar
5, // Width of (moveable) scroll box
0, // Minimum value of Scrollbar
480); // Maximum value of Scrollbar
add (scrollHeight); //Add Scrollbar to window
/* OPTIONAL: Set size of Scrollbar in pixels in window. Begin by removing the automatic layout
manager for the window - the automatic manager produces a very small bar in an inconvenient
position. However, any other components will need to be positioned in the same way. */
setLayout(null);

//Now set the position and size of the Scrollbar manually


scrollHeight.setBounds(
500, //Top left x position
20, //Top left y position
15, //Width in pixels
480); //Length in pixels

//Now listen to the Scrollbar in adjustmentValueChanged


scrollHeight.addAdjustmentListener (this);

//Repeat all of the above for a horizontal Scrollbar


scrollWidth = new Scrollbar(Scrollbar.HORIZONTAL, 200, 5, 0, 480);
add(scrollWidth);
scrollWidth.setBounds (20, 500, 480, 15);
scrollWidth.addAdjustmentListener (this);
}

public void paint (Graphics g)


{
g.drawString("Height is " + height, 20, 50);
g.drawString("Width is " + width, 20, 65);
g.drawOval(20, 20, width, height);
}

public void adjustmentValueChanged (AdjustmentEvent e)


{
//Get value of each Scrollbar and set width, height to corresponding Scrollbar values.
if (e.getSource() == scrollHeight) height = e.getValue();
if (e.getSource() == scrollWidth) width = e.getValue();
repaint();
}
}
Keyboard events (including the KeyListener interface)
Java applets can respond to the press of various keys on the keyboard, without the need for a
TextField. For example, you will often want to program the escape or direction keys, and you may
also want to program the various funcion keys. The following program is a very simple introduction
to how you can access these keys.

It uses the method keyTyped to get the value of a “normal” letter or digit key.
It also uses the method keyPressed to identify which key has been pressed, and includes the “action
keys” such as the function and arrow keys, Home, Page Up etc. In the window are printed the value
of the letter or digit key if one of these has been pressed, and the name of the key that has been
pressed.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class KeyDemo extends Applet implements KeyListener


{
char ch;
String sr;
public void init ()
{
requestFocus (); //make applet the active component for key
events
addKeyListener (this); //listen to key events
}
public void paint (Graphics g) {
g.drawString("The character typed is " + ch, 20, 30);
g.drawString("The name of the key pressed is " + sr, 20, 50);
}

/*Each of the following three methods must be declared whether or not they are used.*/

/*keyPressed responds to pressing anY key on the keyboard, including the "action keys", which
include arrow and function keys, Home, End, Page Up, Page Down, Num Lock etc */
public void keyPressed (KeyEvent e) {
sr = e.getKeyText (e.getKeyCode()); //return a string describing the key
ch = ' '; //a convenient value if a character key is not pressed.
repaint();
}

//keyTyped responds to the character keys


public void keyTyped (KeyEvent e) {
ch = e.getKeyChar(); //character that is pressed
repaint();
}

//keyReleased reponds to releasing any key


public void keyReleased (KeyEvent e) {} //key released

}
Mouse events: MouseListener interface
A very important class of events are those events generated by the computer mouse. These actually
use the MouseListener interface.

The following program is about the shortest program you can write using a MouseListener. It simply
tells you the coordinates of the cursor in the Applet window, and is available under the Outlook
public folders.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Mouse1 extends Applet implements MouseListener


{
int x, y; //coordinates of mouse

//Demonstrates the use of mouse events using MouseListener


public void init()
{
addMouseListener(this);
}

public void mousePressed (MouseEvent e)


{
//This applet responds to mousePressed
x = e.getX();
y = e.getY();
repaint();
}

//The other interface methods used by MouseListener must be defined, even if they are not
used.
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}

//Indicate position of mouse


public void paint (Graphics g)
{
g.drawString("Mouse is at (" + x + "," + y + ")", x,y);
}
}

You will notice that to use a mouse you must:


 import java.awt.event.*
 add “implements MouseListener” to the class header
 include “addMouseListener(this) in init()
 add all of the following procedures (whether or not you use them):

public void mousePressed (MouseEvent e) {}


public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
The actions listened to by each of these procedures are as follows:

mousePressed – mouse pressed down


mouseClicked – mouse pressed down and allowed to click up again
mouseReleased – mouse was down and is released
mouseEntered – mouse is in the Applet window
mouseExited – mouse is outside the Applet window.

You can add the following lines to the previous program to make use of these other methods:

String event; //Declare a string which is used to indicate the type of event

public void mousePressed (MouseEvent e) //response to mousePressed

{
x = e.getX();
y = e.getY();
event = "Pressed";
repaint();
}

public void mouseClicked (MouseEvent e) //response to mouseClicked


{

x = e.getX();
y = e.getY();
event = "clicked";
repaint();
}

public void mouseReleased(MouseEvent e) //reponse to mouseReleased


{
x = e.getX();
y = e.getY();
event = "released";
repaint();
}

//mouseEntered indicates if the mouse is within the applet


public void mouseEntered (MouseEvent e){
showStatus("Mouse inside applet area");}

//mouseExited indicates if the mouse is outside the applet


public void mouseExited (MouseEvent e) {
showStatus("Mouse outside applet area");}

//Indicate position of mouse and whether mouse has been pressed, clicked or released
public void paint (Graphics g) {
g.drawString("Mouse "+event+" at (" + x + ", " + y + ")",x,y);
}
}

Mouse events: MouseMotionListener interface


MouseMotionListener is another interface which includes the following methods:
 mouseDragged tells if the mouse is being moved with its button pressed
 mouseMoved tells if the mouse is being moved with its button not pressed
To use these methods you must implement Mouse motion listener by including it in the class header
and you must add MouseListener in init(). For example:

public class Mouse3 extends Applet implements MouseListener, MouseMotionListener {

public void init()


{
addMouseMotionListener (this);
addMouseListener (this);
}

Here is the code that you can add to the previous program to listen to mouse movements:

//mouseDragged indicates if mouse is being dragged


public void mouseDragged (MouseEvent e)
{
x = e.getX();
y = e.getY();
event = "dragging";
repaint();
}

//mouseMoved indicates mouse being moved


public void mouseMoved (MouseEvent e)
{
x = e.getX();
y = e.getY();
event = "moving";
repaint();
}

Using the mouse to draw on the screen

mouseMoved and mouseDragged enable you to draw in the Applet window using the mouse. To do
this you need to use the “update” method using the code:

public void update (Graphics g) {paint(g);}

Normally, when repaint() is called it completely clears the screen of all previous graphics and paints
the new information onto the resulting clean screen. If you use the update method, repaint() leaves
previous graphics on the screen. Hence, if you are drawing a line using the mouse the Applet window
will remember the previous lines drawn on the screen.

The following code (added to the previous code) allows you to draw a series of circles in the window
which follow the motion of the mouse. The distance between successive circles depends on how fast
the mouse is moving, and on how frequently the particular computer can call the repaint() method.

//draw small circle at position of mouse


public void paint (Graphics g)
{
g.fillOval(x-2, y-2, 4,4);
}

To draw a continuous line, you can use the following paint method (along with the previous code):
public void paint (Graphics g)
{
g.drawLine(oldX, oldY, newX, newY);
}
Here:
 newX and newY give the current x and y coordinates of the mouse (as obtained using the
method getX(), getY() in mousePressed.

 oldX and oldY give the previous x and y coordinates: the program draws short lines from the
old to the new coordinates.
Practical exercises
1. Complete all of the programs suggested above. To remind you these are:

1. Print out the position of the mouse (Mouse1) as in the first complete example.
2. Print out the mouse events in mouseListener
3. Print out the mouse events in mouseListener and mouseMotionListener
4. Draw a series of circles which follow the movement of the mouse
5. Draw a continuous line which follows the movement of the mouse.

These are all available for your checking in outlook under the Mouse folder, with names Mouse1,
Mouse2, Mouse3, Mouse4 and Mouse5.

2. Write a program which will let the user draw a series of connected straight lines in the Applet
window. You will need to use mouseListener, and you will need to store the previous x and y values.
The sample solution is the program “Lines” in Outlook.

3. Write a program which draws a line from the current position of the dragged mouse to a suitable
fixed origin near the bottom left of the screen. This line represents a vector of the type you may have
found in maths and science. At the head of the vector, print out the angle it makes with the
horizontal. You will need to use mouseMotionListener and you will also need to use Math.PI and
Math.atan(angle in radians).

The maths is as follows, where origX and origY are the coordinates of the origin – but try to work it
out yourself before you use the answer. In this maths the angle is in degrees and the length is in
pixels.
angle = Math.atan((double)(origY - y)/(x - origX))*180/Math.PI;
length = Math.sqrt((origY - y)*(origY - y) + (x - origX)*(x - origX));

This is what a small section of the Applet window might look like

You will be using this technique later on when you write some games programs in which you wish to
launch a ball / missile / billiard ball etc at a target.
Exercise 18 Java Notes: Control Structures

Conditional statements
If statement:
If (<boolean expression>) <statement>
Simple examples:
if (x < 5) g.drawString(“hello”, 20, 40);
if ((x < 5) && (y > 23)) g.drawString(“hello”, 20, 40);
if (x == 4) num = 45 + x;
if (doAgain) repaint(); //doAgain must be a boolean variable
if (e.getSource() == input) count++;

Compound if statement
If you want more than one statement to be executed when the “if” condition is true, you must bracket
them in braces {}, otherwise only the first statement will be executed.
Syntax
if (<Boolean expression>) {
Statement1;
Statement2;
<More statements>;
}

Nested if statements
Conditional statements can be nested. For example:

if (<Boolean 1>)
if (<Boolean 2>)
if (<Boolean 3>)
<statement>;

is equivalent to:
if (<Boolean 1> && <Boolean 2> && <Boolean 3>)
<statement>;
if .. else statements
Syntax:
if (<Boolean 1>) <statement1>;
else if (<Boolean 2>) <statement2>;
else if (<Boolean 3>) <statement3>;
…..
else <final statement>; //optional last line

There is a big difference between the two sections of code in the following example:

if (marks > 40) if (marks > 80) g.drawString(“Great”,20,40);


g.drawString(“Pass”,20,40); else if (marks > 60)
if (marks > 60 ) g.drawString(“Credit”,20,40);
g.drawString(“Credit”,20,40); else if (marks > 40)
if (marks > 80) g.drawString(“Pass”,20,40);
g.drawString(“Great”,20,40);

The first section of code has three separate if statements which are all tested separately. For
example, if marks was equal to 45 the code would print out “Pass”, “Credit” and “Great” – not the
intention. The second section of code contains one if statement and the program leaves the statement
after the first true condition. For example, if “marks” was equal to 45 it would print out “Pass” and
then exit the statement.
The “dangling” else
General rule:

An “else” goes with the nearest “if” that precedes it.

Here is an attempt at a program which is supposed to write out “Pass” if the marks are between 50
and 60 and “Fail” if they are below 50:

if (marks > 50)


if (marks < 60)
showStatus(“Pass”);
else showStatus(“Fail”);

In this case, the else goes with the preceding “if (marks < 60)” so in spite of the way that the program
is written, the computer actually interprets it like this:

if (marks > 50)


if (marks < 60)
showStatus(“Pass”);
else showStatus(“Fail”);

In this case, there is no print out for the case when marks are less than 50, and “Fail” is printed out
for those students who get more than 60 marks. The problem is referred to as a ”dangling else”
problem.

We can overcome this problem in a number of ways:

1. Bracket the second “if” statement:

if (marks > 50) {


if (marks < 60)
showStatus(“Pass”); }
else showStatus(“Fail”);

2. Reorganise the logic:

if (marks < 60)


if (marks > 50)
showStatus(“Pass”);
else showStatus(“Fail”);

Switch statements
Switch statements provide a convenient shorthand for a series of if statements in which each
statement tests if a variable has one particular value.

Basic syntax:
Switch (<expression>)
{
case <expression value> : <statements>;Can be more than one, without braces
case <different value> : <statements>;
..
..
case <different value> : <statements>;
}
Some things to know about switch statements:

1. Because each case tests for an equality, you cannot use real numbers in the case expression. In
the same way, you can't put comparisons in the case label.
2. You cannot duplicate the case condition.
3. Unlike a series of if..else conditions, a switch statement executes every case condition after the
first true case condition unless you tell it to jump out of the loop using the break command.
4. You can include more than one value in each case label, using the following syntax:
case <value1>: case <value2>: case <value3>: <statement>;
5. You can insert a default at the end of the list of case labels which is executed if it is reached,
using the syntax:
default: <statement>;

An example:
Switch (dayOfWeek)
{
case 1: case 7:
g.drawString("Weekend", 20, 40);
rate = 2; break;
case 2: g.drawString("Monday", 20, 60); break;
case 3: g.drawString("Tuesday", 20, 60); break;
case 4: g.drawString("Wednesday", 20, 60); break;
case 5: g.drawString("Thursday", 20, 60); //break omitted
case 6: g.drawString("Friday", 20, 60); //break omitted
default: g.drawString("Number out of range", 20, 60);
}

In this case, the if the day falls on a weekend, the program sets the rate (of pay presumably) to 2 and
breaks out of the switch statement. If it is a then continues on to the correct day. It will only reach the
default if the number entered is out of the weekday range, and in this case it will print out an error
message. Because there is no “break” with cases 5 and 6 (as their should be) if it gets to case 5 and
case 5 is true, it will continue to execute case 6 and the default regardless of whether case 6 is true or
not.

Programming exercises 18
(See also the simple programming exercises you have already done in Introductory Exercises 11 and
12.)
1. Set up a TextField in an Applet window into which the user types single characters. Maintain
a tally of the letters, digits and spaces which you print out in the window.

2. Extend the previous exercise to include a tally of upper case letters and lower case letters.
This will probably involve some nested if statements.

3. Employees are categorised as A, B, or C classifications. Payment rules are as follows:

A : Salary fixed at $1500 per week regardless of hours worked.


B : Wage is $1000 per week plus $40 dollars per hour for all hours worked over 35 hours.
C : Wage is $30 per hour worked.

Write a class which has inputs for the employee category and the hours worked. The program
evaluates the salary of each employee for the week and also tallies up the total salary bill for
the week.
Your program should:

 Accept ‘a’, ‘A’, ‘b’, ’B’, ‘c’, ‘C’ as valid inputs to the character category.
 Print out a warning message for any other input.

Theoretical exercises 18
In the following examples you may assume that all variables have been correctly declared as having
the appropriate type, including boolean type.

1. What are the output of the following code? How would you fix it?
if (gender == 1)
showStatus(“Woman”);
else;
showStatus(“man”);

2. What is the output of the following code if age = 70 and if age = 50? How would you fix the code
to print out pension if and only if the age is greater than or equal to 65?
if (age >= 65);
showStatus (“Pension”);

3. What is the output (if any) of the following code if a person is


a. 16 years old.
b. 18 years old and a citizen
c. 18 years old and not a citizen?

if (age >= 18)


if (citizen)
showStatus(“Can vote”);
else showStatus(“Cannot vote’);

4. What is a more efficient (ie uses less logic operators) way of stating the boolean conditions in the
following statements. Your studies of logic might help you here!
(a) if (!(x < 19) && !(y > 3)) < statements>;
(b) if (!(x < 19) || !(y > 3)) < statements);
(c) if ((x > 20 && y > 3) || (x > 20 && y < 0)) <statements>
(d) if (!(x >=20) && (!(x <= 10)) <statements>

5. Find the mistakes in the following code, assuming that months 5 to 10 are cold, the other
months (1 to 4 and 11 to 12) are warm and months 9, 10 and 11 are spring. You don’t have to
worry about situations that are not covered by the code.

if month > 4 && month <= 10


g.drawString(“The weather is cold”, 20, 40);
if (month > 8) g.drawString(“It is spring”, 20, 60)
else g.drawString(“The weather is warm”, 20, 40);

6. Walter J. Nerd needs a computer to tell him what to do. His plans are that:
a. If the temperature is below 15 and it is raining he will stay at home and play computer
games. However, this will damage some of his neurons.
b. If the temperature is above 30 he will go to a nice air conditioned computer shop and buy
some more computer games. However, this will reduce his bank balance.
c. Otherwise he will go to the house of his friend Wallace W. Squareyes and play computer
games, as well as drinking all of Wallace’s cola.
Here is his attempt at programming the computer to tell him what to do:
if (temp < 15)
if (raining)
{
g.drawString(“Stay at home”, 20, 20);
neurons--;
}
else if (temp > 30)
{
g.drawString(“Go to shop”, 20, 40);
balance --;
}
else
g.drawString(“Go to Wallace”, 20, 40);
g.drawString(“Drink Wallies’ cola”, 20, 60);

What will the computer tell Walter to do if:


 The temperature is 12 and it is raining.
 The temperature is 12 and it is not raining.
 The temperature is 20 and it is not raining.
 The temperature is 35 and it is raining.
 The temperature is 35 and it is not raining.

How would you fix up the program to do what Walter wants? Try it (the program, not the
lifestyle)!

7. Find the mistakes in the following code. There are lots of them!
switch 4*m + 2
{
case 14: num = 1;
case m>3: num = 2;
case 3: case 14: num = 3;
default: num = 5;
case 18; num = 6;

8. Rewrite the following code using a switch statement.


if (m == 1) g.drawString(“Number 1”, 20, 40);
else if (m == 2) g.drawString(“Number 2”, 20, 40);
else if ((m == 3) || (m = 4)) g.drawString(“Numbers 3 and 4”, 20, 40);’
else g.drawString(“Try again”, 20, 40);

9. Consider the following switch statement:


switch (selectValue)
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue); break;
case 2: setBackground(Color.green); break;
case 3: setBackground(Color.yellow);
case 4: setBackground(Color.cyan);
default: setBackground(Color.magenta);
}
What is the final background colour for all possible values of selectValue, including values outside
the range 0 to 4.

10. Repeat the previous question for the following alternate code:

switch (selectValue)
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue); break;
case 2: setBackground(Color.green);
case 3: setBackground(Color.yellow);
case 4: setBackground(Color.cyan);break;
default: setBackground(Color.magenta);
}

11. Repeat again for this version of the code:

switch (selectValue)
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue);
case 2: setBackground(Color.green);break;
case 3: setBackground(Color.yellow);
case 4: setBackground(Color.cyan);break;
default: setBackground(Color.magenta);
}
The for loop

A for loop allows you to repeat a programming sequence until some condition is met. The for loop
can be expressed as:
for (variable declaration ; boolean expression ; control statement)
<statement>;

The simplest type of for loop uses a simple counting variable. Examples are:

for (int n = 1; n <= 10; n++) sum = sum += 5; //counting up


for (int n = 100; n > 0; n -= 5) <statement>; //counting down

Some important points to note about for loops:


1. The loop variable is local to the loop and cannot be accessed outside the loop.
2. If you want more than one statement to be executed in the “for” loop you must enclose them
in braces {}, otherwise only the first statement will be executed.
3. The Boolean expression can be any valid Boolean expression, and can in theory get quite
complex. However, the as a matter of good programming, the programmer should always be
able to tell how the loop behaves just by looking at the loop statement.
4. You can nest for loops. For example, to print out a 12  12 times table (as in introductory
exercise 13_4) you would write:

for (int i = 1; i <=12; i ++)


for (int j = 1; j <= i; j++)
g.drawString(Integer.toString(i*j), 25 + 25*i, 25+25*j);
5. It is technically possible to change the loop variable in the loop statements. However, this is
generally considered to be bad programming because it makes the program very difficult to
follow.
In a for loop the sequence is as follows:

1. The loop variable is declared and initialised.


2. The Boolean conditions are tested. If false the loop exits.
3. If the Boolean conditions are true, the main statement is executed with the current value of
the loop variable.
4. The control statement is then executed.
5. The Boolean expression is then tested and the loop cycle continues.
It can be important to keep this sequence in mind. For example consider the following loop which is
intended to perform the integer division 100/6 by repeated subtraction of 6 from 100, counting out
the number of times 6 can be subtracted before reaching 0.
int quot, n = 100;
for (int i = 1; n > 0; i++)
{
n -=6;
quot = i;
}
g.drawString("Quotient = " + quot, 20, 40);

If you run this, you will get a final quotient of 17 rather than the expected 16 indicating that the loop
has run 17 times rather than 16. The reason for this is that after 16 runs the value of n is 100 – 16*6 =
4 so that the Boolean is still true and the loop runs once more. The final value of n before the loop
exits will in fact be –2.
Incidentally, the above simple example illustrates a few more points about for loops:
1. The Boolean condition did not involve the counter.
2. The loop used multiple statements which had to be enclosed in braces.
3. We could not print out the value of the loop variable outside the loop. To retain this variable
we had to declare another variable quot which will retain its value outside the loop.

Break and continue


Break is used to exit a loop. For example, the following loop executes only 5 times:

int joe = 0;
for (int n = 1; n <= 10; n++)
{
joe++;
g.drawString(""+joe, 20, 40+10*n);
if (n == 5) break;
}

Continue is used if you want to start the next loop sequence without finishing off the current one.
For example, in the following loop only the values of n which are not divisible by 3 are printed out.
for (int n = 1; n <= 10; n++)
{
if (n%3 == 0) continue;
g.drawString(""+n, 20, 40+10*n);
}

While and do loops


Basic syntax:
while (<Boolean expression>)
<statements with {} braces if more than one>

do <statements>
while (<Boolean expression>);

“While” statements are similar to for statements, and in fact a “for” statement can almost always be
written as a “while”.
As an example, the following two sections of code are equivalent:
for (int n = 1; n <= 10; n++) int n = 1;
g.drawString(“”+n, 20,40); while (n <= 10) {
g.drawString(“”+n, 20, 40);
n++;}

A “while” statement checks the Boolean expression first, and if it is false the subsequent statements
do not run. On the other hand, a “do” statement always executes the loop statements once before it
checks the Boolean condition. Program errors or crashes can result if the Boolean was actually false.
As an example, what happens in the following two sections of code?
int num = 100, n = 10; int num = 100, n = 10;
while (n > 0) { do {
quot = num/n; quot = num / n;
n--; n--;
g.drawString(“”+ quot, 20, 40);} g.drawString(“”+ quot, 20, 40);
}while (n > 0);
Because of the greater scope for errors in using do/while loops, it is generally best to avoid them:
stick to using for or while loops whenever you can.

As a point of programming style, you will often use braces with a do statement to emphasise the fact
that the “while” belongs to the previous “do” – even though this is not strictly necessary. For
example, the following two sections of code are equivalent though the second uses a better
programming style:

int fact = 1, n = 1; int fact = 1, n = 1;


do do {
fact = fact * n; fact = fact * n;
n++; n++;
g.drawString(“”+fact, 20, 40); g.drawString(“”+fact, 20, 40);
while (n < 10); } while (n < 10);

“break” and “continue” in while and do loops


As with for loops, “break” causes the program to exit the loop immediately and continue skips any
remaining statements in the body of the structure and proceeds with the next iteration of the loop.

Note the following difference between the way in which “continue” operates in different types of
loop. (This is a subtle point and will probably not be examined.)

Sequence of steps in for loop Sequence of steps in while and do/while


loops
1. continue 1. continue
2. perform loop increment statement 2. evaluate loop continuation test
3. evaluate loop continuation test 3. perform loop increment statement

Theoretical exercises
1. How many times do the following loops run:
(a) for (int n = 1; n < 10; n++) <statement>;

(b) for (int n = 1; n < 10; n++)


for(int m = 1; m < 5; m++)
g.drawString (“” + n*m, 20, 40);

(c) for (int n = 1; n < 10; n++)


for (int m = 1; m < n; m++)
g.drawString(“” + n*m, 20, 40);

(d) int prod = 1;


for (int n = 1; prod < 100; n ++)
{
prod = prod * 10;
quot = n;
}

(e) //An example of bad programming: why?


//What is printed out?
for (int n = 1; n < 10; n++)
{
g.drawString(“The value of n is “ + n, 20, 20+15*n);
n *=2;
}
2. Find the errors in the following code:

(a) for (double x = 0.1; x != 1; x+=0.1) <statement>;


(b) for (int x = 100; x >= 1; x++) <statement>;
(c) for (int x = 1; x < 10; x++)
g.drawString(“The value of x is “ + x, 20, 40 + x*10);
g.drawString(“The value of x*x is “ + x*x, 60, 40 + x*10);
(d) do
quot = divisor/n;
n--;
while (n > 0);
(e) while (true) <statement>;
(f) while (x < 10)
g.drawString(“The value of x*x is “ + x*x, 20, 40);

3. What is printed out from the following code:


for (int n = 1; n <= 10; n++) {
g.drawString( “” + n, 20, 40+10*n);
if (n*n > 30) break;}

4. What is printed out from the following code:


for (int n = 1; n <= 20; n+=2) {
if (n%3 == 0) continue;
g.drawString(""+n, 20, 40+10*n);}

5. Rewrite the following as a while and as a do/while statement. Careful!


For (int n = 0; n < 20; n+=4)
g.drawString(“Hello”, 20, 40+5*n);

6. The following code evaluates a table of triple products:


int prod;
for (int n = 1; n <= 8; n++)
for (int m = 1; m <=3; m++)
for (int p = 1; p <= 4; p++)
{
prod = n*m*p;
g.drawString(""+ prod, 18*p+ 120*(m-1), 20*n);
}

(a) How many times does the code run before exiting?
(b) What is the largest value of prod?
(c) What does the drawString method do in this code? Try it!
More Programming exercises
4. Primes
Print out all of the prime numbers less than 6000.
To do this, note that:
 A prime number is one that has no divisors except for itself and 1. In other words, when
you divide any number into it there will be a remainder.
 To check if a number is prime, you need only check the remainder for integer division by
divisors less than or equal to the square root of the number you are testing.
Some programming considerations
 Your program will have to have nested for loops. For each number less than 6000 you
will need to test division by all suitable divisors.
 Once you find a divisor for a number there is no point in continuing in that for loop, and
you should break out of the for loop.
 You will probably want to declare a boolean which indicates whether or not a number is
prime.
 You will need to pay careful attention to your program layout – especially the coordinates
in your g.drawString statements – and you will need to use the Project Manager Edit to
set the size of the Applet window.

5 A graph plot
Write an Applet which plots out any quadratic.

This is a tricky program, but it does illustrate some important programming concepts, particularly
in relation to setting up scales in your Applet windows. You can use these concepts in later
programs to do things like plotting out house plans or projectile trajectories.

To make it a bit easier, you can proceed in a number of steps:

(a) Working in pixels with y = 0.003*x2


Set up a rectangle between coordinates (0,0) and say (600, 600) in the window. Draw the x and y
axes through the middle of this rectangle.
Now you can plot out the graph of y = 0.003 * x2 using a pixel scale. You will need to declare two
sets of variables:
x = actual x coordinate of graph
y = actual y coordinate of graph
xPlot = screen coordinate for x, xPlot
yPlot = screen coordinate for y, yPlot
xPlotOld = previous value of x screen coordinate
yPlotOld = previous value of y screen coordinate
Now plot the graph by drawing (very short) straight lines from the old x and y coordinates to the new
ones, using code such as:
for (x = -300; x <= 300; x = x + 10) //lines about 10 pixels
{
y = 0.003 * x * x;
xPlot = (int) (x + 300); //adjust to graph coordinates
yPlot = (int) (300 - y);
g.drawLine(xPlotOld, yPlotOld, xPlot, yPlot);
xPlotOld = xPlot; //get ready for next plot
yPlotOld = yPlot;
}
You should enter your own details. For example, if you make the line segments less than about 10
pixels long the graph will be smoother but will take longer to plot.
This will leave you with one annoying problem, which is easy to fix: when the for loop runs for the
first time, xPlotOld and yPlotOld will be set to the default values of 0, and there will be a straight
line from the top left to the beginning of your actual graph. You can fix this in init() or otherwise.
(b) Plotting any quadratic in pixels
The next step is to add TextFields to allow the user to type in the a, b and c coefficients of the
quadratic, which are still in pixel units. You might need to adjust the position of the graph area to
avoid overlaps between the components of the Applet and the graph.

Because you are working in pixels, you will need to enter coordinates such as a = 0.002, b = 0.5 and
c = -200 to get a decent plot.

You should also tell the program not to plot any points that lie outside the graph borders. Do this
when you have got everything else going.

(c) Plotting the quadratic with “real” coordinates


Now you must change the scale of the graph coordinates so that the user can enter realistic values
such as a = 2, b = -2 and c = 3 and plot out sensible graphs (try these figures with the previous
program!).

Suppose that we want the graph to plot between x = -10 and x = +10, y = -10 and y = +10. Since in
both the x and y directions a range of values of 20 must be scaled up to 600 pixels, we will need to
multiply all of the pixel units by the scale factor of 600/20 = 30.You will also have to adjust the
range of x values in the for statement.

(d) Final touches


Your program so far has included a number of “assumed” numerical values. These include:
 the left, right, top and bottom borders
 the minimum and maximum values of x and y
 the increment between successive values of x in the for loop.

Your program will be much more versatile if you declare variables for all of these numbers,
including variables for the x and y scale factors, and initialise the values of these numbers in init() or
in the declaration section. You could even add TextFields so that the user can alter some of these
values.

Text fields are initially blank, and blank text fields will crash the program. Add a “reset” button
which sets all of the text field values to “0”.

You might also consider adding grid lines or labelling the axes. And why not extend your program to
cover other types of graphs as well?
Exercise 19 Classes and Objects
Summary of terms used in this unit:

What are objects and classes?


Object
 A combination of data and methods used on that data.
 Objects that we have dealt with include strings, the various applet components such as
buttons, colors, fonts and so on.
 As an example if stringVar is an object of the String class, the data stored in stringVar is the
text such as “Hello” and the methods are all the methods associated with the String class,
such as stringVar.length();

Class
A general computer program which carries a “design” or “blueprint” for an object, and so enables a
programmer to create or “instantiate” any number of objects of this class.

Instantiating an object
When you want to use an object in a class you must
 Declare the object by giving it’s class and identifier name:
eg Button myButton;
By convention the class name begins with a capital while the object name begins lower case.

 Instantiate the object by calling one of the constructor methods for the object with the new
method: classes will often have a number of different constructors which take different
parameters, and you can look up the constructors for different objects in the Java API help.
The constructor method always has the same name as the class, but there may be any number
of parameters.Examples are:
myButton = new Button(“Hello”);

What are principles of object-oriented programming (OOP)?


1. Encapsulation
Related data and methods are grouped together in an object in such a way that a programmer
can use the object without having to worry about its details, or running the risk of destroying it.
Data and methods which the user does not need to worry about are “hidden” (declared as
“private”) while “public” data and methods are available in a way which is simple and safe.

2. Inheritance
A “parent” class can be extended to “child” classes which include more data and methods. In
this way the programmer can set up a hierarchy of classes, without necessarily needing to know
the internal details of parent classes. For example, when you create an applet class you are
extending the Java class Applet, and you do not need to know any details of how the Applet
class was originally set up.

3. Polymorphism
If similar classes have the same method name, whenever that method is called for a particular
object Java “knows” to get the version of the method defined in the appropriate class.
First example – a very simple class
On the opposite page is an example of the use of a user defined class and its objects within a larger
program. The class Olympian allows the main program to use objects which store the name, sex and
country of different Olympian athletes.

This is a very simple program, and you might wonder what the fuss is all about. But be patient – you
will see some more involved programs later.

The Olympian class (This is the user defined class included in the main class Olympic)
Lines 19 onwards:
These lines form the class definition. Notice that by convention the name of a class begins with a
capital letter, while objects belonging to the class begin with a lower case letter.

Line 20
This defines a public variable (or property) of the Olympian class. We can access this directly using
notation such as jim.name.

Lines 21 and 22
These define private variables within the Olympian class. These variables cannot be accessed (by
name) outside the class, though the data contained within them can be accessed by the getSex() and
getCountry() methods of the class.

Lines 24 to 26
Here we define a constructor for the class. This is a public method which is used by the external
program to instantiate a new object of that class. The constructor always has the same name as the
class, though the number of parameters can vary. In this case, the constructor has two parameters
which are used to set sex and country of the object when it is instantiated.

Lines 28 to 32
These specify two public methods which return the data stored in the object. In this particular
example, it seems (and probably is) rather pointless going to all this trouble when we could access
the data by making the variables age and country public rather than private. However, this concept of
data hiding is central to object oriented design, because it protects the raw data from mistakes made
by the outside programmer. In this case the programmer has decided that the variable (property)
name can be made public, whereas sex and country should be hidden.

Lines 28 to 41
These specify public methods for setting the data stored within an object.

The Olympic class


This is the “main program” which makes use of the Olympian class.

Line 4
This declares two objects, jim and joe, of the Olympian class

Lines 6 and 7
This instantiates the objects jim and joe using the new operator and the constructor defined in the
Olympian class. Notice that the constructor method must be called with appropriate parameters
which set the initial values of sex and country.

Lines 8 to 11
These use the setSex(), setCountry() and set Name() methods to change the data stored in the objects.
Lines 12 and 13
These obtain the data from each of the objects using the name property for the public variable and
the getSex() and getCountry() methods for the private variables.

1. import java.applet.Applet;
2. import java.awt.*;

3. public class Olympic extends Applet {

4. Olympian jim, joe;

5. public void init(){


6. jim = new Olympian(‘F’, “USA”);
7. joe = new Olympian(‘M’, "NZ");
8. jim.setSex(‘M’);
9. joe.setCountry(“Germ”);
10. joe.setName(“Joe Bloggs”);
11. jim.setName(“Jim Spriggs”);
12. }

13. public void paint(Graphics g) {


14. g.drawString(jim.name + “ “ + jim.getCountry() + " " + jim.getSex(), 20, 40);
15. g.drawString(joe.name + “ “ + joe.getCountry() + " " + joe.getSex(), 20, 60);
16. }
17.
18. }

19. class Olympian {


20. public String name;
21. private char sex;
22. private String country;
23.
24. public Olympian (char s, String c) {
25. sex = s;
26. country = c;}
27.
28. public char getSex() {
29. return sex;}
30.
31. public String getCountry() {
32. return country;}
33.
34. public void setSex(int s) {
35. age = s;}
36.
37. public void setCountry(String c) {
38. country = c;}..
39.
40. public void setName(String n){
41. .. name = n;}
42. }
Second example – an extension of the Olympian class
This is an extension of the previous Olympian class. The only difference is that it has three different
constructors (lines 32 to 41).

Notice that
 all constructors have the same name as the class;
 the constructor methods are overloaded by having different sets of parameters.

These constructors are called from the main Olympic class in lines 9, 13 and 16. An example of each
different constructor is provided.

In line 20 note that joe does not have a country when the getCountry() method is called. When Java
is asked to provide non-existent object data it returns the default value which is “null” in the case of
a String and “0” in the case of a number.

1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class Olympic2 extends Applet {
5.
6. Olympian jim, joe, jill;
7.
8. public void init(){
9. jim = new Olympian();
10. jim.setName("Jim Spriggs");
11. jim.setSex('M');
12. joe = new Olympian('M', "NZ");
13. joe.setName("Joe Bloggs");
14. joe.setCountry("Germ");
15. jill = new Olympian("Jill Hill", 'F', "France");
16. }
17.
18. public void paint(Graphics g) {
19. g.drawString(jim.name + " " + jim.getCountry() + " " + jim.getSex(), 20, 40);
20. g.drawString(joe.name + " " + joe.getCountry() + " " + joe.getSex(), 20, 60);
21. g.drawString(jill.name + " " + jill.getCountry() + " " + jill.getSex(), 20, 80);
22.
23. }
24. }
25.
26. class Olympian {
27. public String name;
28. private char sex;
29. private String country;
30.
31. public Olympian (){}
32.
33. public Olympian (char s, String c) {
34. sex = s;
35. country = c;}
36.
37. public Olympian (String n, char s, String c){
38. name = n;
39. sex = s;
40. country = c;}
41.
42. public char getSex() {
43. return sex;}
44.
45. public String getCountry() {
46. return country;}
47.
48. public void setSex(char s) {
49. sex = s;}
50.
51. public void setCountry(String c) {
52. country = c;}
53.
54. public void setName(String n){
55. name = n;}
56. }

Super

You may remember that the Java word this refers to the current object. Similarly the word super
means the superclass of the current object.
A class often needs to invoke a method from its immediate superclass or one of the classes further up
the inheritance tree. The methods in all classes up the inheritance tree are freely available (provided
that they are labelled as public or protected). The only problem that can arise is when the desired
method in the superclass has the same name as a method in the current class. The solution is for the
subclass to prefix the method name required with the word super.

In the following example the current class has a method called calculate, and within that class is a
call to another method called calculate from its super class.

public void calculate() {


…….
super.calculate();
.……
}

Inheritance
One of the very important features of object oriented design is inheritance, the ability of one class to
inherit important features of another class without the need to repeat the code of the “parent” class.
Inheritance is accomplished using “extends”.

The code opposite shows three classes which inherit from the Olympian class. In each case note that:

 Since the name of the constructor must be the same as the name of the class, the constructors
are not inherited from the parent class and must be defined in each child class. It also follows
that if the constructors use private variables, these must be redefined.
 Public methods defined in a parent class are passed on to the child class.

Class Track is a child of the class Olympian and stores the additional data distance and time, and
defines the methods for setting and getting this data. Since the constructors variously take time,
distance and country as parameters, these must all be redefined in the class. However, sex is inherited
from Olympian as are all of the other methods of Olympian.

Class Water is a child of the class Track, and stores the addition data stroke, as well as the
appropriate methods for setting and getting this data. Since sex and country are used in the
constructors, they must be redefined in this class.

Class Team is a child of the class Olympian and stores the additional data game, as well as
appropriate methods for this data. Since game is the only parameter in the constructors, the inherited
data sex and country do not have to be defined in this class.
Note that if we never intend to use the parent class Olympian in the program, using instead its child
classes, it is not necessary to define constructors for the Olympian class.

The relationships between the classes can be represented in a class hierarchy as shown:

Olympian

Track Team

Water
Exercises 19
 Devise a class for gymnasts which holds the usual information about name, sex and country
and also adds sport information.
 Devise a Soccer class which stores information on positions played as well as whether the
player is a captain or vice captain.
 Where would you put a class to include members of water relay teams? You might end up
with a bit of polymorphism in your methods!
 Suppose that you want to store information on all of the members of a soccer team. How
would you set up an array of Soccer objects (corresponding to each of the members of the
team)? Write a method for getting a list of all of their names and their positions, with the
captain and vice captain at the head of the list.
class Track extends Olympian
{

private double time;


private int distance;
private String country;

public Track () {};

public Track (int d, double t, String c)


{
time = t;
distance = d;
country = c;
}

public void setTime(double t)


{
time = t;
}

public void setDistance(int d){


distance = d;}

public double getTime() {


return time;}

public int getDistance() {


return distance;}
}

class Water extends Track


{

private String stroke;


private char sex;
private String country;

public Water (char s, String c)


{
age = a;
country = c;
}
}

class Team extends Olympian {

private String game;

public Team () {}

public Team (String g){


game = g;}

public void setGame (String g){


game = g;}

public String getGame (){


return game;}
}
Objects & Classes- exercises
Object-oriented programming is about constructing programs from objects. An object is a
combination of some data (variables) and some actions (methods).

Suppose we are designing a computer game of “golf” then one of the program objects would be a
golf ball, another could be the holes. Every golf ball created will be an instance of the golf ball
object.

The program will have to display a ball to the screen, move it and let the user know when the ball has
been sunk. Suppose the ball is identified as “sunk” by changing colour.

1. What data variables would you need to associate with the golf ball object to determine its size
and position? Write the code to declare these variables.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________

2. Write the method that will display the golf ball to the screen. Call it drawBall
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________

Initialization and construction


When a ball is first created, the position and size of the balloon need to be given some values. This
is called initialising the variables. One good way to do this is to initialise the variables in their
declaration, as usual, like this:
Private int diameter = 10; and so on.
An alternative way is to write a special method to do the initialising. This is called a constructor
method.

3. Complete the following constructor method for the golf game project
public GolfBall (int initialDiameter, int initialX, int initially) { Note – the
diameter = _______________________ constructor
method must
________________________________
have the same
________________________________ name as the class
________________________________
Classes
As many golf balls are going to be created we need a basic description / plan / blueprint of how to
create a ball. The declaration of the structure of all balls is called a class. A class is a generalization
of an object. Each time a new ball is created we say it is an instance of the class. Below is the code
for the class GolfBall as we have defined is so far.

4. Include the code for an applet called GolfGame that creates one instance of GolfBall.
(Remember to treat it like all other objects so far). Where would this code be written?
class GolfBall
{

int diameter;
int xcoord, ycoord;

public GolfBall (int diameter1, int xcoord1, int ycoord1)


{
diameter = diameter1;
xcoord = xcoord1;
ycoord = ycoord1;
}

public void drawBall (Graphics g)


{
g.fillOval (xcoord, ycoord, diameter, diameter);
}

4. Write a line of code that will make the golf ball red and note where this code will go in the
above Applet.
5. Write the code that will move the golf depending on where the mouse is clicked as shown
below

Mouse click
position

Golf ball

Direction of ball movement

8. Write the algorithm that will draw the golf course – background colour and holes
9. Write the code to draw the golf course
10. Write an algorithm that will determine when a ball has been sunk and that it will change
colour when sunk
11. Write the Java code to determine when a ball has been sunk. Include a Boolean variable that
will be true when sunk and false otherwise
12. Write the code that make the golf ball red if sunk and yellow otherwise
Summary: GUI objects
 To create (instantiate) an object use the constructor with new.
For example, myButton = new Button(“Hello”).
 To add an object to the Applet window use add.
For example add (myButton).
 To listen to an object (if available) you must
o implement the appropriate interface in the class definition
o tell the class to listen to that object in init()
o use the appropriate method to respond to events.

Interface (to implement) Listen Respond to events


ActionListener addActionListener() public void actionPerformed (ActionEvent e) {}
ItemListener addItemListener() public void itemStateChanged(ItemEvent e) {}
AdjustmentListener addAdjustmentListener() public void
adjustmentValueChanged(AdjustmentEvent e) {}

 To control the layout of a GUI object you must include the following code:
setLayout( null); //removes automatic layout
objectName.setBounds(int topleftX, int topleftY, int width, int height);

In the following summaries “name” refers to the name of the appropriate object.

Label
Constructor Label (String s) Values for “alignment” are:
Label (String s, int alignment) Label.LEFT Label.CENTER Lavbel.RIGHT
Implements Not applicable
Other Methods name.getText()
name.setText( String s)

Button
Constructor Button (String s)
Implements ActionListener
Other Methods

TextField
Constructor TextField( int columns)
TextField( String s)
TextField(String s, int columns)
Implements ActionListener
Other Methods name.getText() To onvert text to number types use, eg
name.setText( String s) int m = Integer.valueOf(fieldname.getText()0.intValue();

TextArea
Constructor TextArea (int rows, int columns) scrollbars can have values:
TextArea (String s) SCROLLBARS_BOTH,
TextArea (String s, int rows, int columns) SCROLLBARS_HORIZONTAL_ONLY
TextArea( String s, int rows, int columns, SCROLLBARS_NONE
SCROLLBARS_VERTICAL_ONLY
int scrollbars)
Implements ActionListener Also TextListener
Other Methods name.setText(String s) Many other methods available
name.setEditable(Boolean canEdit)
Choice Buttons (“Drop Down List”)
Constructor Choice()
Implements ItemListener
Other Methods name.add(String item) add is repeated for each item in the drop down list.
name.getSelectedIndex() Returns the index (int) of the selected item.

CheckBox (Single box with a space for a “tick”)


Constructor CheckBox (String s)
Implements ItemListener
Other Methods name.getState() Returns true or false if Checkbox is ticked

CheckBoxGroup (“Radio Buttons”) – only ONE button can be selected at any one time
Constructor CheckboxGroup() Constructor for the whole group
Checkbox( String s,  s is the String displayed for each button
CheckboxGroup c,  c is the name of the group of buttons
boolean state);  state is the initial state of each button: if more than
one is set true initially, only the last one remains true.
Note that you must add the group and each Checkbox within
the group
Implements ItemListener
Other Methods

List
Constructor List (int rows, boolean many) rows is the number of rows visible. If there are more rows
these will be accessed by a scroll bar.
many is true if more than one item can be selected at any one
time.
Implements ActionListener
Other Methods name.add(String s) Adds new item to the list
name.getSelectedItem() Returns a String, the name of a single selected item
name.getSelectedItems() Returns a String array of selected items.

Scrollbar
Constructor Scrollbar (int orientation, ScrollBar.VERTICAL or ScrollBar.VERTICAL
int value, Initial value of Scrollbar
int visible, Amount value changes if clicked
int minimum, Minimum value of Scrollbar
int maximum) Maximum value of Scrollbar
Implements AdjustmentListener
Other Methods name.getValue(); Returns value of Scrollbar
Examples of setting up various GUI objects

GUI objects implementing ActionListener, or which cannot be listened


to
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Objects extends Applet implements ActionListener


{
//Declare objects
Label myLabel; //cannot listen to Labels
TextArea myArea; //cannot listen to TextArea
Button myButton;
TextField myText;
List myList;

public void init()


{

//Set up myButton
myButton = new Button(" This is a Button "); //create
add(myButton); //add to window
myButton.addActionListener(this); //listen

//Set up myArea
myArea = new TextArea(4,15); //create
add(myArea); //add to window
myArea.insert("This is a TextArea", 12); //add some text to the area

//Set up myLabel(note that you can't listen to a label)


myLabel = new Label(" This is a Label "); //create
add(myLabel); //add to window

//Set up myText
myText = new TextField(" This is a TextField ");//create
add(myText); //add to window
myText.addActionListener(this); //listen

//Set up List (in this case three items, multiple choices not allowed
myList = new List(3, false); //create
myList.add("First list item"); //add items to the list
myList.add("Second list item");
myList.add("Third list item");
add(myList); //add to window
myList.addActionListener(this); //listen
}

//actionPerformed must be stated, even it it does not contain


code
public void actionPerformed (ActionEvent e){}
}
GUI objects implementing ItemListener
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Objects extends Applet implements ItemListener


{
//Declare objects
Checkbox myCheck1, myCheck2; //separate Checkboxes
CheckboxGroup myGroup; //group of Checkboxes //configured as Radio
//Buttons
Checkbox item1, item2, item3; //Checkboxes in group: only //ONE can be on at
any time
Choice myChoice; //Choice items

public void init()


{
//Set up myCheck1: a single Checkbox
myCheck1 = new Checkbox("This is a Checkbox”);//create
add(myCheck1); //add to window
myCheck1.addItemListener(this); //listen

//Set up myCheck2: another independent Checkbox


myCheck2 = new Checkbox(" This is a Checkbox "); //create
add(myCheck2); //add to window
myCheck2.addItemListener(this); //listen

//Set up myGroup as a group of Radio Buttons. Only one button can be


//selected at any time. Initially all buttons are OFF ("false")
myGroup = new CheckboxGroup (); //create group
item1 = new Checkbox(" Item1 ", myGroup, false); //create buttons in
//group
item2 = new Checkbox(" Item2 ", myGroup, false);
item3 = new Checkbox(" Item3 ", myGroup, false);
add(item1); //add group buttons
add(item2);
add(item3);
item1.addItemListener(this); //listen to group
item2.addItemListener(this);
item2.addItemListener(this);

//Set up choice items: These appear in a drop down menu


myChoice = new Choice(); //create
add(myChoice); //add to window
myChoice.add("Choice 1"); //add options
myChoice.add("Choice 2");
myChoice.add("Choice 3");
myChoice.addItemListener(this); //listen to choice

//itemStateChanged must be stated, even it it does not contain code


public void itemStateChanged (ItemEvent e){}
}
Sample questions from mid year papers

GYC 2002 Section D: Criterion 7

Question 10

Consider the code for an Applet given below. Draw a rough sketch of what you would expect the
output from the Applet to look like on the screen. Be sure that you clearly distinguish between
buttons, labels and textfields.

import java.applet.*;
import java.awt.*;
public class ExamQuestion10 extends Applet
{
Label prompt;
Button buttonA, buttonB, buttonC;
TextField nameText;
public void init()
{
prompt = new Label("Enter your name");
buttonA = new Button("Do something");
buttonB = new Button("Do something else");
buttonC = new Button("Exit");
nameText = new TextField ("Enter your name here");
add(prompt);
add(nameText);
add(buttonC);
add(buttonA);
add(buttonB);

}
public void paint(Graphics g)
{
}
}

Question 11

The class below has been defined in Java as follows:

class Person
{

String firstName, surname;


String gender;

public Person(String gender, String firstName,String surname)


{
this.gender=gender;
this. firstName = firstName;
this. surname = surname;
}
public String get_name()
{
return firstName+” “+surname;
}
public String get_gender()
{
return gender;
}
}

(a) A student wishes to create Person objects in an Applet. The required objects are:

William with a surname of Smith.


Mary with a surname of Poppins.

Show how these objects could be created.

(b) The student would also like to see if the objects have been correctly created so they decided to
print the first name, surname and gender of each person onto the screen. How could this be
accomplished
from the Applet?

Question 12

The student decided to create some further objects as defined in the hierarchy below.

Person

Athlete Academic Labourer

For the following two questions, a and b, you will need to decide what additional member variables
and member methods would be appropriate to describe the new sub classes.

(a) Write the definition for the sub class Athlete, and then show how Peter Smith, a state champion
high jumper would be created (instantiated).

(b) Write the definition for the sub class Academic, and then show how Peter Jones PhD, a physics
professor could be created (instantiated).

(c) Explain using examples from the above classes, what the role of super and this are in the
construction of classes and sub-classes.
Launceston College 2004 Section D Criterion 7
Question 10
In Java we use constructors to create objects in the Applet window.
Below is more detail on a number of commonly used object constructors.
The diagram opposite contains a number of these objects:
Constructors
1. Button Constructors:
2. Button() creates and empty button
3. Button(String) creates a button with a specific label.
4. myButton.setBounds(int, int, int , int) sets the position of the
Button in the window.
5. myButton.setEnabled(Boolean) sets the Button to enabled or disabled.
6. Choice Box Constructors:
7. Choice() creates an empty multi-choice box.
8. myChoice.add(String) adds the given string as a selection to the myChoice choice list.
9. TextField Constructors
10. TextField() creates a new textfield.
11. TextField(int) creates a new textfield able to hold a specified number of characters.
12. TextField(String) creates a new textfield initialized with a specific text.
13. TextField(String, int) creates a new textfield initialized with a specific text and able to hold a
specified number of characters.
14. All the above Constructors have these methods
15. thisObject.setBounds(int, int, int, int) sets the position of the object in the window.
16. thisObject.setEnabled(boolean) sets the object to enabled or disabled.
17. thisObject.setBackground(int, int,int) sets the red, green, blue colours for the object.
18.
(a) You want to use the setBounds(int, int, int, int) method to set out your components in the applet
window. How must you set the layout?
(b) Write statements to declare and instantiate a button called goButton with the following properties:
i. The button has the label “Go”.
ii. The button of width 50 and height 30 is positioned at the coordinates 100, 300.
iii. The button is disabled.
iv. The button is added to the applet window.
v. The button is activated to listen for user actions.

(c) Write the Java code you would use to create a Choice box with a list of colours (red, green, blue),
activate it and add it to the applet window.
(d) Sketch the textfield that would appear in your applet window from the statements:
myField = new TextField(“Enter name”, 15);
add(myField);
(e) A method belonging to the TextField class is the setText(String) method. What is its purpose?

Question 11
The questions below refer to the following lines of code.
class Flight
{
protected int flightNumber;
protected double departureTime;
protected String destination;
public void setCoords(int initialFNumber, double initialDTime,
String initialDestination)
{
flightNumber = initialFNumber;
departureTime = initialDTime;
destination = initialDestination;
}

public String getDestination()


{
return destination;
}

public void display(Graphics g)


{
g.drawString(“Flight Number: “ + flightNumber, 10, 10);
g.drawString(“Departure Time: “ + departureTime, 10, 40);
g.drawString(“Flight Number: “ + destination, 10, 60);
}
}

a) You have an applet that uses Flight objects. Write a statement that would declare and instantiate a
new Flight object called myFlight that has a flight number 111, destination Paris and departure
time 11.20 am.
b) You add the following statement to your applet:
myDestination = myFlight.getDestination();
What would the value of the variable myDestination be?
c) Write a method for the Flight class that would allow you to get the flight time of myFlight.

Question 12
Consider the following class.

class Alien extends SpaceShip


{

public void resize(int initialWidth, int initialHeight)


{
super.width = initialWidth;
super.height = initialHeight;
}
}
a) Explain what it means to extend another class?
b) Explain the line in class Alien:
super.width = initialWidth;
c) The class Spaceship contains a method moveShip(int x, int y) and you have instantiated
an Alien called myAlien. Write a statement that uses the moveShip() method to move myAlien
to co-ordinates 100, 50.
Exercise 20 Arrays
An array is a numbered sequence of items which are all of the same base type.
The type of the individual elements in the array is called the base type of that array. The base type of
an array can be any legal Java type – a primitive type or a class.
Java arrays are objects. This means that arrays are created using the new operator.
No variable can ever hold an array, a variable can only refer to it.
Since int[ ] is a class, it can be used to declare variables:
eg int [ ] list; // creates a variable named list of type int[ ]
This variable is capable of referring to an array of ints, but initially its value is null. Use the new
operator to create a new array object, which can then be assigned to list.
The syntax for using new with arrays is:
<variable name> = new int[ array length];
eg list = new int[5]; // creates an array of five integers

T h e a r r a y o b je c t c o n t a in s 5 in t e g e r s
lis t : (5 ) lis t .le n g t h
c a lle d lis t [ 0 ] e t c .
0 lis t [ 0 ] It a ls o h a s lis t .le n g t h w h ic h g iv e s t h e
n u m b e r o f it e m s in t h e a r r a y .
0 lis t [ 1 ] N o t e : lis t .le n g t h c a n n o t b e c h a n g e d .

0 lis t [ 2 ]

0 lis t [ 3 ]

0 lis t [ 4 ]

T h e s t a t e m e n t " lis t = n e w in t [ 5 ] " ;


c r e a t e s a n a r r a y w h ic h c a n h o ld
5 in t s , a n d s e t s lis t t o r e f e r t o it

The number of items in an array is called the length of the array. The length of the array list can be
referred to as list.length and in this case would be 5.
The position number of the item in the array is called the index (or subscript) of that item. The
index of the first item in an array is always 0. If the length of the array is N then the index of the last
element is N-1. Once an array has been created its length cannot be changed.
The syntax for referring to an item in an array is:
array-variable [integer-expression]
so list[0] would refer to the first element in the array list, and list[4] the last if an array list had a
length of 5.
In Java, once an array is created it is always filled with a known or default value:
For integers this is zero
booleans is false
char is the character with Unicode number zero and
objects is null
Each one of the items in an array can be used just like a variable :
 values can be assigned to it eg list[1] = 46.4
 it can be used in expressions eg total = total + list[i]
eg total = total + list[i*3]
 it can be passed as a parameter in subroutines
To print out the items in an array, list, using the paint method:
for (int i = 0; i < list.length: i++)
{
g.drawString(“” + list[i], xpos, ypos);
xpos = xpos + 10;
}
This loop will end after painting list[4], because once i = 5 it will no longer be less than list.length
(of 5 in this case).
There are 2 possible errors which can occur when accessing an array:
A null pointer error will occur if the value of the list is null, so list does not even refer to an
array. Trying to access say list[i] will produce this error.
Array index out of bounds error will occur if list does refer to an array but the value of the
index is outside the legal range of values (in our example
if i < 0 or if i > = list.length).
You can declare and initialise an array variable in one step:
eg int[ ] list = new int[5];
and the array items will have the default values of eg zero for integers.
You can also initialise an array with a specific list of values:
eg int[ ] list = { 1, 5, 7, 8, 12, 45 };
where the new list has the 6 values above, list points to this new array and list.length is known to be
6. Items in list do not have to be constants, they can be variables or expressions as long as their
values are of the same base type.
eg int[ ] list = { 1, 5*2, xx, 8, 12, 45 }; where xx is an int which has been initialised.
You can assign a new value to an array variable, list, that has been declared earlier using:
eg list = new int[ ] { 12, 24, 36, 48, 60, 66};
Note: You may see int[ ] list; correct Java syntax <type-name> < variable- name>
is sometimes written as int list[ ]; (a hangover from C, C++ and Pascal syntax)
Array Processing Techniques
Processing an array means applying the same operation to each new item in the array – usually with
a for loop
Applet code to add 5 numbers stored in an array called a.
int a [ ] = {6, 7, 9, 12, 4}; // give initial values to an array called a
public void init( );
{
total = 0; // total starts at 0
for ( int i = 0; i < a.length; i = i + 1 ) // only use < a.length here because if
// i = a.length you will get an “array
// out of bounds error”
total = total + a[i] ;
}
To count the number of items in an array that meet a certain condition (eg that the items are
even numbers)
int a [ ] = {6, 7, 9, 12, 4}; // give initial values to an array called a
public void init( );
{
count = 0; // count starts at 0
for ( int i = 0; i < a.length; i = i + 1 )
{
if ((a[i] % 2) == 0)
count = count + 1;
}
}
To count the number of times an item is the same as the next item in the array a
use the code above replacing if ((a[i] % 2) == 0) with if (a[i] == a[i+1)
Remember that the loop can only be repeated up to a.length –1 times because otherwise there would
be an “array out of bounds error”.

Finding The Largest (Or Smallest) Item In An Array.


To find the largest (or smallest) item you create a variable called max (or min) and initially set it to
the value of the first item in your array a.
double max = a[0]; min = a[0];
for ( int i = 0; i < a.length; i = i + 1 )
{
if (a[i] > max) or if (a[i] < min)
max = a[i]; min = a[i];
} // at the end of this loop max is the largest item in the array a or
// min would have the smallest.

Binary Search
works on a sorted array. Check if item being searched for is greater than or less than a middle value.
You can then eliminate half of the array from being searched. Progressively halve the part of the
array to be searched, until the item is found, or you find the item is not there.
Making A Copy Of An Array
In some computer languages it is possible to make a copy of one array using:
double[ ] b = a; This is not correct in Java since all it does is declare a new array
variable and make it refer to the same object to which a refers.
ie a change to a[i] will make the same change to b[i] as well !!!
To make a new array b that is a copy of a, you must make a new array object and copy each of the
individual items from a into the new array b.
double[ ] b = new double[a.length]; // make a new array object the same size as a.
for ( int i = 0; i < a.length; i = i + 1 )
b[i] = a[i]; // move a copy of a[i] into b[i]
It is possible to only partially fill an array with useful data but you must keep a count of the number
of items in the array.

Sorting An Array
There are a number of different sorting strategies. We will look at the bubble sort. When sorting
items such as integers in an array a, you need to compare a[i] and a[i + 1]. To swap 2 values around
in the array you need to have another variable called hold to temporarily hold one of these values.
See below:
if (a[ i ] > a[i + 1])
hold = a[ i ];
a[ i ] = a[i + 1];
a[i + 1] = hold;
A bubble sort requires you to progressively compare elements next to each other in an array, and (if
you are sorting into ascending order) to place the lower number in the position with the lower index.
// Sorting an array into order using the bubble sort method.
public class sort extends Applet
{
int a[ ] = {6, 5, 4, 3, 2, 1};
boolean finished;
int i, j, xpos, hold;
public void paint(Graphics g)
{
//sort array into order
while (finished == false)
{ finished = true;
for(i = 0; i < a.length - 1; i++)
{ if (a[i] > a[i+1])
{ hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
finished = false;
}
}
}
//output sorted array
xpos=100;
g.drawString("Sorted Array is",20,80);
for(j=0;j<=a.length-1;j++)
{ g.drawString(a[j]+"",xpos,80);
xpos = xpos+30;
}
}
}
To bubble sort an array of strings rather than integers.
Use as your array a:
String a[ ] = {“Greg”, “Geoff”, “Anthony”, “Murray”, “Dorothy”, Wags, “Henry”};
In the bubble sort algorithm, when comparing 2 items which are strings, you cannot use if (a[ i ] > a[i
+ 1]) which is what you used for integers, use a[i].compareTo(a[i+1])
a[i].compareTo(a[i+1]) will result in a number < 0 if a[i] is < a[i+1] as for example if item a[i]
contained “Ant” and item a[i+1] contained “Dog”.
The reason for this is that the comparison is made using the ASCII numeric code for the characters
eg ‘A’ is 65 and ‘C’ is 67 and on comparison, 65 – 67 gives an answer of –2 which is less than 0.
Don’t worry about this but I’m just explaining why.
Other sort or ordering strategies for arrays:
Insertion Sort works on a sorted array. The item to be added to the list is inserted into the
appropriate place in the sorted list and all the items higher than the new item
will move up one place in the array.
Selection Sort works on an unsorted array. If the array is to be sorted into ascending order,
then the largest item is found and moved to the last position in the array. The
next largest item is found and moved to the second last place etc.
Shuffle There are times when you may need to make a sorted array in random order ie
to shuffle as in card games
// Shuffles an array into random order. From David Eck
public class shuffle extends Applet
{
int a[ ]={1, 5, 8, 56, 89, 99, 100}; //sorted array
int j, xpos, temp, randLoc;
public void paint(Graphics g)
{
//shuffle the array
for(int lastPlace = a.length-1; lastPlace > 0; lastPlace--)
{ // choose a random location (0 .. lastPlace)
randLoc = (int)(Math.random()*(lastPlace + 1));
temp = a[randLoc];
// swap items in locations randLoc and lastPlace
a[randLoc] = a[lastPlace];
a[lastPlace] = temp;
}

//output unsorted array


xpos=100;
g.drawString("Unsorted Array is ", 20, 80);
for(j = 0; j <= a.length-1; j++)
{ g.drawString(a[j] + "", xpos, 80);
xpos = xpos + 30;
}
}
} // end of shuffle

Two-Dimensional Arrays
A two-dimensional array is an array of arrays of a particular type.
An array of ints has the type int[ ] and an array of arrays of ints has the type int[ ] [ ]. It is possible to
have 3 or more dimensional arrays but we will stick to 2-dimensional ones.
To declare a variable aa of type int[ ] [ ] and to initialise it to refer to a newly created object use:
int [ ] [ ] aa = new int[3] [4];
where int[3] [4] can be thought of
as a grid of ints with 3 rows and 4 columns
aa:
(4 )
If you create an array 1 0 12 -1
aa = new int[3] [4], aa: 1
7 -3 2 5
you should think of it as a -5 -2 2 9
(3 )
0
"matrix' with 3 rows and
12
4 columns
-1
Really, aa holds a reference to an array
of 3 items, where each item is a reference
to an array of 4 ints.
Remember that arrays start with an index of 0, (4 )
so to refer to the fourth item in the third row use: (4 ) 7
aa[2] [3] which has the value 9. -3
-5
Note: aa.length gives the number of rows of aa;
-2 2
aa[0].length gives the number of columns.
2 5

9
A 2-dimensional array can be created as a list of array initialisers, one for each row in the array.
The array aa shown on previous page can be created using:
int [ ] [ ] aa = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, 9 }
};

Two-dimensional arrays can be used wherever data naturally falls into rows and columns:
eg grid on a chess board
students and test scores
monthly sales from a number of branches of a store.
To process all the items in an array you need a for statement nested inside another.
Using the array aa with the following definition:
int[ ] [ ] aa = new int[3] [4]
you could store a 1 in each location of aa with the following code:
for (int row = 0; row < 3; row++)
{
for(int column = 0; column < 3; column++)
{
aa[row] [column] = 1;
}
}
The first time the outer loop executes with row = 0, the inner for loop then fills in the four values in
the first row of aa. The outer loop executes with row = 1 and fills in the four values in the second
row of aa etc.

To add up all the items in aa eg tests of students


int sum =0; // total of all scores of all students
for (int student = 0; student < 3; student ++)
{
for (int test = 0; student < 3; student ++)
{
sum = sum + aa[student] [test];
} // end of inner for loop
} // end of outer for loop
Arrays programming exercises 20
Sample solutions for these programs are in Outlook in the “Arrays” folder.

1. The test marks for the students in a class are as shown:

54, 37, 89, 23, 65, 58, 23, 59, 92, 64, 43, 39, 60

Write a program which has methods to determine the:

 maximum mark for the class


 minimum mark for the class
 average mark for the class
 standard deviation of the class marks (see formula in box).

As well as this write a method to place the marks in ascending order.

2. The individual players in a sports team obtained the following points in matches with five other
teams. The results are plotted in the following table, with the names of the players in the top row and
names of the opposing teams in the left hand column:

Joe Jim Fred John Jack Jake


Baddies 10 4 0 15 20 6
Goodies 3 16 12 4 23 12
Goons 13 20 4 12 13 8
Monty 4 9 15 11 10 13
Python 3 12 14 0 11 9

(a) Introductory program:

To begin with, write a class which will:


 read the above data into three arrays, including one dimensional arrays for the names of the
players and opposing teams and a two dimensional array for the scores.
 Print out the number of rows and number of columns for the two dimensional table.

(b) Final program:


Once you have got this going, write methods which will
 determine the total score for any player in all matches (the method should include the number
or name of the player as a parameter);
 determine the total score for the team in any match (the method should include the number or
opposing team name as a paramter);
 determine which player scored the most points;
 determine which game (name of opposing team) gave the greatest total score.
Problems in Arrays 20
1.
(a) The number used to refer to a particular element of an array is called its _________ or its
__________________.
(b) An array index always has type _____________.
(c) The first element of an array always has index value of ___________.
(d) A single array can store variables of type int and variables of type float. True / False?
(e) Which of the following types can be stored in an array?
int float String double Button TextField Label
char bool
(f) What programming processes are involved in the following lines of code:
 int[] days;
 days = new int[7];
 for (int n = 0; n < 7; n++) days[n] = 0;
 int[] days = new int[7];
 int[] days = {0,0,0,0,0,0,0};

2. Consider an array which has been declared and initialized as follows:


int[] marks = {70, 50, 40, 67, 23, 82, 45}

What are the values of:


(a) marks[2]
(b) marks.length

3. Consider an array which has been declared and created as follows:

int[] days = new int[7]

(a) How many different values are stored in the array?


(b) What is the value of days.length?
(c) What is the range of indices used in this array?
(d) What (if any) values are currently stored in the array?
(e) Where is the mistake in the following line of code:
for (int n=0; n<=7; n++) days[n] = 3;

4. How would you declare and initialize a String array which stores the names of the days of the
week?

5. A teacher wishes to store both the names of his 18 students and the marks they obtained in a
test. Declare and create arrays (you will need two of them) which will store all this information.

6. What is the final value of the int variable mystery in the following program:

int[] guess = {2,3,4,5,6};


for (int n = 0; n < guess.length; n++) mystery = mystery + guess[n];

7. What does the following program excerpt do (assuming everything else is correctly set up).

String[] days = {“Mon”, “Tues”, “Wed”, “Thur”, “Frid”, “Sat”, “Sun”};


for (int n = 0; n < 7; n++) g.drawString(days[n], 20, 20 + 15*n);
8. What is the final value of the int variable mystery?

int[] values = {5,4,8,2,9,6};


int mystery = 0;
for (int n = 0; n < 6; n++)
if (values[n] > mystery) mystery = values[n];

9. Consider the following code which has lines numbered for convenience:

1 Button[] digit = new Button[10];


2 for (int n = 0; n < 10; n++) {
3 digit[n] = new Button(Integer.toString(n));
4 add(digit[b]);}

(a) Describe the result of the code as it stands.


(b) What is the function of “new” in line 1?
(c) What is the function of “new” in line 3?
(d) What code would you add to make the program “listen” to each of the Buttons? Where should
this code be placed?

10. Consider an array which has been declared and initialized as follows:

int[][] table = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}};

(a) What is the value of table[2][0]?


(b) What is the value of table[0][2]?
(c) What is the value of table.length?
(d) What is the value of table[0].length?
(e) What is the value of table[0]? How would you print this out?
(f) What is the final value of count in the following code:

int count = 0;
for(int n = 0; n < 3; n++)
for(int m = 0; m < 2; m++)
if( table[n][m] > 2 ) count++;

11. An array is declared and created as follows:


int[][] table = new int[4][4];

What values are stored in table after each of the following sections of code.
(a) for (int n = 0; n <4; n++)
for (int m = 0; m < 4; m++)
table[n][m] = n;

(b) for (int n = 0; n <4; n++)


for (int m = 0; m < 4; m++)
table[n][m] = m;

(c) for (int n = 0; n <4; n++)


for (int m = 0; m < 4; m++)
table[n][m] = n*m;
12. Declare and create an array to represent a chessboard, which has 8  8 squares. Each square
will be represented by a string.

13. The following table represents the scores obtained by 6 different football teams over 4 weeks of
matches.

Tigers Lions Bears Cats Snails Frogs


Week 1 3 2 0 1 3 2
Week 2 1 0 4 2 0 4
Week 3 2 1 1 1 4 2
Week 4 3 1 2 3 1 1

Write code that will:

i. Declare, create and initialize the scores in an array.


ii. Determine the total score of Snails in all four matches.
iii. Determine the total score of all teams in week 3.

14. Write code that will set up a 6  6 array in which the values stored are 0 if the sum of the
indices is odd and 1 otherwise.
Exercise 21 Characters and Strings
Summary of char variables
Comparing variables of type char with strings
char String
Variable type Primitive type Object
Speed of processing Fast Slower than char
Notating ‘A’ “A”
Assigning char charVal = ‘A’ String s = “Hello”;
String s = new (“Hello”);
Testing equality if (charVal == ‘A’)… if (s.equals(“Hello”))…
Special characters
‘\n’ newline (“enter”) character (does not work in drawString())
‘\t’ tab character (does not work in drawString())
‘\u’ unicode character
\” used to indicate that “ is part of a string and not the beginning or end of a string.
Casting between types char and int
charVal = (char) 65; charVal = ‘A’ (65 is the ASCII and Unicode value of
‘A’)
numVal = (int) ‘A’ numVal = 65.
Methods in class Character
If ch is the name of a character variable then the following methods can be used:
 Character.isLetter(ch) returns the Boolean true if ch is a letter, false otherwise.
 Character.isDigit(ch) returns the Boolean true is ch is a digit, false otherwise.
 Character isLetterOrDigit(ch) returns the boolean true if ch is a letter or digit.
 Character.isLowerCase(ch) returns true if ch is a lower case letter.
 Character.isUpperCase(ch) returns true if ch is an upper case letter.
 Character.toUpperCase(ch) returns a char having the upper case value of ch.
 Character.toLowerCase(ch) returns a char having the lower case value of ch.
Strings
Declaring and initialising strings
All of the following are valid declarations:
String S1, S2;
String S1 = “Hello”;
String S1 = new (“Hello”);
After declaration, a string can be assigned a value in the following ways:
S2 = “Goodbye”;
S2 = new (“Goodbye”);
Assigning values to Strings
A string can be given a new value of different length. For example:
String S1 = “Hello”;
S1 = “Goodbye;
S1 = S2;
Strings can be concatenated using +:
S1 = “Hello” + “ “ + “to you.”;
S1 = S1 + “Jim”;
Comparing Strings
Since Strings are objects, they cannot be compared using == and other such symbols. They require
methods of the String class.

Equality: if (string1.equals(string2)) <do something>;


if (string1.equalsIgnoreCase(string2)) <do something>;

Comparing int n = “ant”.compareTo(“ant”) the two strings are the same, value of n is 0
int n = “ant”.compareTo(“bee”) “ant” precedes “bee” so value of n is
negative
int n = “bee”.compareTo(“ant”) “ant” precedes “bee” so value of n is positive
int n = “Bee”.compareTo(“ant”) “Bee” precedes “ant” (capitals have smaller
Unicode values) so n is negative.
Changing Strings
Suppose we have defined a string
String string1= “ Hello “:
Then:
 string1.toUpperCase() has value “ HELLO “.
 string1.toLowerCase() has value “ hello “.
 string1.replace(‘e’, ‘u’) has value “ Hullo “.
 string1.trim() has value “Hello”.

In each case we can replace the string variable with an actual string, such as:
 “Hello”.toUpperCase() has value “HELLO”.

Concatenating Strings
To concatenate Strings, the easiest method is to use +:
newString = string1 + string2 + “Hello” + string3;

There is also a concat method, an example being “Hello”.concat(“goodbye”);

Other primitive types are concatenated as Strings provided they are preceded by a String:
newString = “” + 1234 + numVar + floatVar;
newString = “The answer is “ + (5 * 20); //In this case the product is
evaluated first //and then converted to a String, so newString has the
value “The answer is 100”

Extracting substrings
substring “Hello”.substring (n) returns the substring from position n onwards .
If n = 1 in this example it returns “ello”.
“Hello”.substring (n,m) returns the substring from position n to position (m – 1).
If n = 1 and m = 3 in the above example it returns “el”.

Properties of Strings
Strings may be regarded as arrays of characters with special properties and methods specified in the
String class. Hence, some of the notation for Strings corresponds with that of arrays, with the
characters being numbered from 0 to (string.length-1).

length “Hello”.length() has value 5.


charAt “Hello”.charAt(0) returns the char value ‘H’.
“Hello”.charAt(4) returns the char value ‘o’.
Exercises 21

1. What is printed out?


s = new String(“hELlo");
g.drawString(s.substring(0,1).toUpperCase() + s.substring(1).toLowerCase(), 20, 20);

2. What is printed out, assuming s1, s2 and s3 have been correctly declared?
s1 = "bat";
s2 = "bee";
if (s1.compareTo(s2) == 0) then s3 = s1;
else
if (s1.compareTo(s2) < 0) then s3 = s2 + s1;
else
s3 = s1 + s2;
g.drawString (s3, 20, 120);

3. What is printed out?


s3="";
String subject[] = {"Maths", "Science", "English", "Latin", "Basketweaving"};
for (int i=0; i < subject.length; i++)
s3 = s3 + " " + subject[i]; //could also use s3 += (“…” + subject[i])
g.drawString(s3, 20, 140);

4. What is printed out, assuming s is correctly declared?


s1 = "bat";
s2 = "frog";
s3 = "bee";
if (s1.compareTo(s2) > 0) {
s = s1;
s1 = s2;
s2 = s;}

if (s2.compareTo(s3) > 0) {
s = s2;
s2 = s3;
s3 = s;}

if (s1.compareTo(s2) == 1) {
s = s1;
s1 = s2;
s2 = s;}
}

g.drawString(s1+s2+s3, 20, 180);

5. What is the value of the following:


(a) “Good bye”.charAt(4);
(b) (int)’A’
(c) (char) 92;
(d) “Good bye”.length();
(e) “Good bye”.subString(3);
(f) “Good bye”.subString(3,5);

6. What is printed out?


g.drawstring(“My name is \”Frog\” and I am very green.”, 20, 60);
Exercise 22 Threads in Games with Animation
Overview
Java programs run in Threads which perform particular tasks. If the program must perform different
simultaneous tasks, these tasks are run in separate threads which are timesliced: each thread controls
the computer for a short time after which the control passes to another thread.

Here are some examples of common animated games with different numbers of threads.

Single Thread
The user sets some object moving across the screen. The user input and the moving object are
controlled by the same thread: once the object is moving, the user can’t do anything to change what it
does.
Snakes and Ladders: The user throws a die which cause a token to jump from square to square and
possibly to slide up a ladder or down a snake.
Golf: The user hits a golf ball which then moves across the screen bouncing off walls and other
obstacles and possibly landing in a hole.
Scientific simulations: some object (such as a golf ball, a rocket, a bullet or anything else) is
launched and follows a pathway mathematically determined by the laws of Physics.

Two Threads
The user is able to control the object while it is moving. The user input is in the “main” program
while the movement of the object is controlled by a separate independent thread.
Snake: The user controls a snake which moves horizontally or vertically in a box. When the snake
collects randomly placed food items it grows in length, but it the snake crashes into the wall it dies.
Tetris: A single “stone” falls down a grid. The user can control its position and orientation and must
try to place it in the best position when it lands at the bottom of the grid.

Three Threads
The “main” program controls the user input and as well as this there is an object which moves in
response to the users input and another object which moves independently around the screen,
Simple “Shoot-em-ups”: The user fires a gun which sends a bullet towards a moving target. The
threads are the interface, the user and the target.
“Pac Man”: the user controls the movement of a pacman which is being chased by monsters. The
threads are the interface, the pacman and the monsters.
Arkanoid: The user controls the movement of a “paddle” which moves left and right firing bullets at
a wall of bricks. The threads are the interface, the paddle and the bullets.
Single player tennis: the user controls a racquet which hits a ball against a wall. The threads are the
interface, the racquet and the balls.

Four Threads
Once again the “main” program controls the user input. However now there are three types of
objects moving independently around the screen.
Shoot-em-ups in which there is the main program, the user object moving around the screen, the
targets which “feed” the user and “baddies” who try to kill the user.
Two player tennis: The threads are the interface, the racquet, the ball and the opposing racquet
(which may be controlled by the computer).

Many Threads
Shoot-em-ups with the user able to fire a large number of bullets, each controlled by a separate
thread.
A summary of the techniques used to control various numbers of Threads
Single Thread
Here the only problem is to introduce delays which will slow down the animation to human speeds.
Two delaying techniques are:

Add a counting loop. This is simple, but the delay will depend on the speed of the computer.
for(int m = 0; m < 2000000; m++)

Put the thread to sleep for a time by inserting a sleep into each loop of the
animation. This will probably occur within a “for” loop (or similar) in paint(). In
the following example, the thread will “sleep” for tChange milliseconds
try{(Thread.sleep(tChange);}
catch (InterruptedException e){return;}

Note that in this case Thread (capital ‘T’) is used, calling to the static Thread method. If a separate
thread has been declared and created the name of this Thread object can be used instead. See below.

A note on Sleep (before we look at multiple Threads)


The sleep method puts the thread to sleep for the specified number of milliseconds. While it is
asleep, other threads can operate. Because (if there is more than one thread running) sleep can cause
an exception it is enclosed inside a try{} block which essentially tells the class to “try to carry out
these instructions”. If the class fails to do this, it then carries out the alternative procedure set out in
the following catch{} block in which the “thrown” exception is “caught”.

In the following example a separate Thread object has been declared, the class implements runnable
(see next section) and sleep is called in run():
thread is the name of the Thread object which has previous been declared
tChange is the sleep time in millseconds
the alternative catch procedure is return from the current loop – other alternatives may be used.

try{(thread.sleep(tChange);}
catch (InterruptedException e){return;}

If a Thread object has not been declared, the alternative code which calls the default Thread and is
often placed in paint() is:

try{(Thread.sleep(tChange);}
catch (InterruptedException e){return;}

Multiple Threads
Here the basic techniques are the same regardless of how many threads are running. But things can
get complicated.

With multiple Threads, things can go wrong!


The producer – consumer problem: a producer thread produces information which is used by a
consumer thread. If the two are not properly synchronised, all sorts of strange things can go wrong. If
you plan to study tertiary computer science, expect a lot more on this one.
Similarly, if two threads are both modifying the same data very strange things can happen if they get
out of synchonisation.
Hopefully, the programs you write will not get too messy, but if you get strange things happening
you might well have a synchronicity problem, which can be hard to fix. The message is plan your
programs carefully if you are using more than one thread!!!
Runnable
The implementation of the Runnable interface provides the simplest way of programming more than
one thread and it is recommended by some texts in all Applet classes.

Here is an outline of the code that you might use to run one extra Thread.

public class myClass extends Applet implements Runnable {


Thread myThread; //declare a new Thread object

public void init() {


myThread = new Thread (this); //create the Thread object
myThread.start();} //start the Thread object

public void run() { //run must be declared


/* Code for each step of the animation.
This will usually include a for or while loop.
You will often find it most convenient to draw into the
current Graphics context avoiding the use of paint(). */

If you are running two or more threads, the code might look something like this.

public class myClass extends Applet implements Runnable {


Thread myThread1, myThread2; //declare a new Thread object

public void init() {


myThread1 = new Thread (this); //create the Thread object
myThread.start();} //start the Thread object
myThread2 = new Thread (this);
myThread2.start();}

public void run() { //run must be declared


if (Thread.currentThread() == myThread1)
processThread1();
else
if (Thread.currentThread() == myThread2)
processThread2();
}

The methods processThread1() and processThread2() will both contain a sleep method for that particular Thread. Once
again, they will often contain a reference to the Applet window Graphics context which avoids the use of paint().

Declaring separate Classes to create the multiple Thread objects


Many textbooks use this approach almost exclusively – even though some suggest it is not the most
appropriate technique for Applets! You will only be able to make sense of this code if you have
mastered the basic techniques of object oriented programming, so don’t attempt this approach until
you know for example what is meant by a class constructor. There is often not a lot of difference in
performance between this technique and Runnable because the classes we create inherit from class
Thread which itself implements Runnable. The differences appear in the coding and in the ability of
the Class approach to have many objects running at once.
The advantages of having separate classes are
All of the code for each Thread object is tucked away in a separate class, so the main program is a lot
simpler.
You can create any number of new and independent objects belonging to the class which do not
interfere with each other. This is sometimes very useful – for example if you want to be able to fire
any number of bullets at a target.

The disadvantage is that there is quite a bit of extra coding.


The new Thread objects have to be declared and created as with Runnable. However, a constructor
must be written in the Thread class and used in the main class.
It is a bit more difficult to share information between the various threads. Some techniques are:
Including properties as parameters in the constructor.
Declaring the properties of the class as public and passing them to and fro between the various
threads.
Including class methods such as getX() and setX(parameter) for private properties.
Declaring properties as static – this is getting complicated and there will be more on this later!
The information which must be passed to the Thread classes from the “main” will often include
The Graphics context
The screen background colour
If one Thread needs to communicate with another Thread, a Thread object must be declared and
created in the receiving class.

Here is the basic code for setting up a new Thread class. In this example the Graphics context and
background colour will be passed from the main class to the Thread class in the constructor
parameters. Your programs might well have different constructor parameters.

Class MyThread extends Thread {


//Public, private declarations, possibly static.
private Graphics g;
private Color c;
//Constructor
public MyThread(Graphics graphics, Color color) {
g = graphics;
c = color;
}
//Run is compulsory when inheriting from Thread
public void run() {
//as before, probably contains a loop and controls
//each step of the animation including the timing.
}

In the main class you must declare, create and start the MyThread object which we will name
myThread (watch the capitals in the first letter). In the example above you might include the
following code in init():
MyThread myThread; //declaration
Graphics gr = getGraphics(); //get the Graphics context
Color col = getBackground(); //get the background colour
myThread = new MyThread (gr,col); //creating object myThread
myThread.start(); //start object myThread

In the main class you can set and get the public Thread variables using code such as:
myThread.variable1 = <value>;
<value> = myThread.variable2;
Stopping a Thread

Note: Some text books use an infinite loop such as for(;;) in run(), and use threadName.stop() to stop the Thread. This
practice has been declared to be dangerous by the developers of Java and if you use stop you will get a deprecated API
message when you build the class. You should avoid stop and instead use a more direct method to stop a Thread.

An animation thread will generally be controlled by some form of loop. When the loop is ended, the
thread will stop releasing the computer resources it was using while alive. You should make sure that
you write code to jump out of the loop.

Some possibilities are”

Run a for loop for a set number of times.


for(int m = 0; m < maxCount; m++) {…}

Run a while loop while some boolean variable is true. The boolean can be set false in many different
ways. For example, the user could type in a character on the keyboard. The user might die on
collision with a wall or monster object in the game.
while(isAlive) {…}

Set up an infinite while or for loop..


while (true) {…} OR
for(;;) {…}

Then use break to break out of the loop or return to go back to the method which called the method
containing the loop.
if (exitCondition) return; OR
if (exitCondition) break;

Some Practice Programs (sample solutions provided in Outlook)

1. Scrolling Text
Write a class in which a text string (with a large font) moves across the screen from right to left.
When the text completely passes from the left of the window, it starts moving again from the right.

2. Simple animation
Obtain a series of animated gif images from http://www.animationfactory.com/
and incorporate them into a simple program which displays each of the images one after the other
(with a sleep time of perhaps 40 mS). It is simplest to create an array of images in your program.
Exercise 23 Graphics in Games with Animation
How do you draw to the screen?
The Graphics context is the computer equivalent of the paper, pencils and rules needed for drawing a
picture. An image is drawn into the Graphics context by calling the various graphics methods such as
 gContext.drawString(String, int, int);
 gContext.drawImage(Image, int, int, this);
and so on.

When you call paint(Graphics g), g is the context for the screen image. Therefore, a call to a method
such as g.drawLine(int,int,int,int) in paint() draws directly onto the screen in the Applet window.

To draw onto the screen (Applet window) without using paint() you must:
Name and create a Graphics object with the current Graphics context (ie the Applet window). In
this case we have named the object “gCurrent” though any other name is possible.
Graphics gCurrent = getGraphics();
Draw into the current context from another method. For example:
gCurrent.drawRect(int,int,int,int);

It is also possible to have an off screen image with its own Graphics context and to draw on this
image. This is the technique used in double buffering.
Double Buffering
If you build up an image component by component on the screen, the image will flicker as each
component is added.
In Double Buffering you create a background (buffer) Graphics context and its image, add all your
components to this buffer and finally draw your complete image to the screen when it is ready.
Steps in double buffering are:
Declare the Graphics context and buffer image:
Image buffer; //buffer image
Graphics gContext; //The buffer Graphics context

Create the Graphics context and the buffer image in init().


w = getSize().width; //Get width of Applet window
h = getSize().height; //Get height of Applet window
buffer = createImage(w,h); //Create the buffer image
gContext = buffer.getGraphics(); //Get the Graphics context for this image

Draw the buffered image into the buffered Graphics context one component at a time. For example:
gContext.drawLine(20, 40, 60, 80);
gContext.drawImage(myImage, 0, 0, this);

Swap (or copy) the final buffered image onto the Applet window in paint().
g.drawImage(buffer,0,0,this);

Update
The update() method controls the painting of an image onto the screen. The default erases the current
image with a blank screen before painting the new image. This causes flicker.
To prevent this erasing, and so to enable the new image to build up over the old image without
flicker, you must override the automatic update function by including the following method in your
program:

public void update(Graphics g){paint(g);}


Using file images
When building up a background to your Applet project you have the following choices:
Build up the image within your Java class – probably quicker to run and certainly provides less
complex programming for simple images.
Copy a file image onto your Applet – could well be quicker for some complex images, and necessary
for “interesting” images that cannot be made easily in Java.

If the precise coordinates of the background are important (for example if the image contains walls
for a moving ball to bounce off) you can proceed as follows:

In Java draw the essential outlines of the image. For example, draw important boundaries using
drawLine and the positions of important components using fillOval and other Graphics methods.
In Paintshop Pro capture this image from the Applet window and save it as a GIF file without
changing the size. (You will have to save with only 256 colours.) You would preferably save it in the
same directory as your Java project.
In Paintshop Pro or other graphics software, add whatever nice effects you want without changing
the size of the image or the position of the crucial coordinates.
In Java draw this image first into the buffered Graphics context and then onto your Applet.

Just to remind you, the important steps in adding a file image to a class are:
Declare the image:
Image background;

Create the image in init(). If the image file is in the same directory as the project use:
background = getImage(getDocumentBase(), "myImage.gif");

Copy the image into the buffer:


gContext.drawImage(background,0,0,this);

Problems with starting the program


When you incorporate an image into a class in which there is some form of animation, the class will
run ahead of the image during the first time it loads, with strange and unpredictable results. To make
the class wait until the image has been successfully loaded, you should incorporate the following bit
of magic code into your class:

Declare an object of type MediaTracker:


MediaTracker imageTracker;

Create the MediaTracker object and use it to force the class to wait until the image is successfully
loaded. The following code is inserted into init() after the creation of the image object.

imageTracker = new MediaTracker(this); //Create the MediaTracker object


imageTracker.addImage(background,0); //name of image being tracked
try {
imageTracker.waitForID(0); //wait until image loaded
}
catch(InterruptedException e){} //just in case there is a problem!

Sample programs available to you in Outlook


In Outlook Public Folders you can look at three classes which illustrate these techniques. In each
case a ball moves diagonally across a background image and stops. The background image is
redrawn before each new image of the ball so that the old ball images are erased.
Flicker1
In this class no attempt is made to use any special techniques to reduce flicker. Notice that the ball
flickers badly and that you can see the background image through it.

Flicker2
In this class, the class repeatedly creates the background image but all available techniques are used
for reducing the flicker.

Flicker3
In this class the background image has been created as a separate image “Flicker.gif” in a file which
is also provided in Outlook. You should download this image into your project directory if you want
to run the program. The effect is much the same as for Thread2. In this case there appears to be little
difference between creating the image in the program and downloading it from a file.
Exercise 24 Notes on games which make use of Thread techniques
Most text books seem to favour a technique which puts the various threads in multi-threaded
programs into separate classes which inherit from the Thread class. However this can lead to difficult
programming, particularly if you are not familiar with the techniques needed to create and use
separate classes in your program.

The three games illustrate the various features of each style of programming.

 Projectile simulation: Since this simulation only requires one thread, the only thread
technique needed is in setting the sleep time for this thread.

 Ball inside a box: The final game (Thread6) uses Runnable to control two independent
threads. In this case, Runnable is perfectly effective and provides the easiest programming.

 Shoot-em-up: The final game (Shoot2) places both the target and bullet objects in separate
classes. This was necessary (in the case of the Bullets at least) in order to enable the user to
fire any number of bullets at any one time. The programming is more complex, but so is the
game.

You can find these programs in Outlook public folders as well as various different versions which
illustrate different approaches to writing the programs.

Projectile simulation (program given to you on Outlook is Projectile)


How the game is played
As written, this is not really a game, though you could easily make it into one by including a
stationary target.
 The user initially sets the velocity and direction of the ball by dragging the mouse.
 When the mouse is released, the ball is launched and moves according to the laws of gravity
until it hits the ground or a wall at a simulated distance of 100m. The “game” is then over.
Structure of the program
Only a single thread is needed to control the program, and all the action is handled in paint().
 Initially, a boolean hit is false, and the if condition in paint() causes a vector line indicating
the position of the mouse to be drawn on the screen.
 When the mouse is released, hit becomes true and the if condition in paint() goes to a loop
which calculates the next position of the ball and draws it on the screen until the ball hits one
of the boundaries.
The program must handle two sets of variables:
 The “real life” variables correspond to the actual position and velocity of the moving ball and
the time interval between successive images of the ball. These must be doubles.
 The “pixel” variables correspond to the position of the ball on the screen and to the integer
time between images in milliseconds.
A note on the calculation
 The basic physics of this program is simply v = u + gt, where g is the acceleration due to
gravity and equals 9.8 ms-2 down.
 The calculation method could be extended to take into account other factors such as wind
resistance and spin. If you want to get into this sort of simulation programming ask your
teacher about the formulas needed.
Other simulation programs
With a few formulas you could simulate all sorts of interesting motions including the motion of balls
through the air, rockets, satellite motion and so on. If you have a scientific bent, this can provide
some very rewarding programming.
Ball inside a box (Thread6)
How the game is played
 The user can move a ball inside a box by pressing the arrow keys.
 If the ball hits the sides of the box the ball dies. In this case the user can start the game again
by pressing the spacebar.
 There is also a target which moves randomly inside the box, and is able to bounce off the
walls of the box.
 The user must make the ball hit the target. The number of times that the ball has hit the target
is printed on the screen.
 The user can kill the target (finishing the game) by pressing the ‘x’ key.

Structure of the program


At any one time there are three threads running, with the ball and target threads controlled by
Runnable as independent named threads in the main class. These are:
 the background thread which controls the user input from the keyboard;
 the ball thread
 the target thread.

The position of the ball and target are global variables which can be used by any of the threads.

Run uses an if..else statement to select which of the ball and target threads to process. Each thread
has its own sleep time.

The threads are stopped by setting a loop control variable (isAliveBall or isAliveTarget) to false and
returning from the relevant loop in run().

Screen components are drawn in the current Graphics context so that paint is not used except for
the printout of the number of times the target has been captured.

Other related programs


Some other programs which are provided in Outlook illustrate different approaches. You can look at
these if it helps you to understand the programming techniques. You should look at Thread3 to
Thread5 if you want to see how the threads can be placed in separate classes.

 Thread1 has only a single thread (controlled by the main class) with no user interaction. The
only use of Thread techniques is to use sleep to control timing.
 Thread2 implements Runnable which enables the ball to be controlled by the user in a named
second Thread. There is no target.
 Thread3 provides an alternative technique which has the same overall effect as Thread2. The
ball is made an object of a separate class Ball which implements Thread.
 Thread4 introduces a target to the game. Both are controlled by the same Thread (in
Runnable) so that when one stops they both stop.
 Thread5 places the target in a separate class so that it moves independently of the ball as a
third Thread.

Programming exercise
Introduce a “monster” thread to the game. A monster moves around the screen trying to catch the
ball. The monster can bounce off the walls. If the monster catches the ball the ball dies.
A good version of the game will have the monster actually chasing the ball and not just moving at
random.
Simple shoot-em-up (Shoot2)
How the game is played
 The user can fire a gun at the bottom of the screen by pressing the spacebar. Each time the
spacebar is pressed a new bullet flies upwards.
 A target moves from right to left across the top of the screen.
 If a bullet hits the target, the target dies in an explosion (very simple!). The user can start a
new target by pressing the ‘m’ key.
 Each time the user fires the gun the ammunition count (which starts at 100) decreases by 1.
The game is over when the user has used up all the ammunition.

Structure of the program


This is an example of a program which must use a separate class, at least for the bullet. Runnable
won’t do. The basic difference is that every time the user fires a bullet a new bullet thread is started,
and there can be many such threads running at any one time each having its own value for yBullet,
the variable which gives the position of the bullet. If you tried to do the same thing with Runnable,
you could create a new Thread each time you pressed the spacebar, but the value of the global
variable yBullet would be changed for all threads. The threads would therefore not run smoothly.

Unfortunately, the program gets rather complicated and you will need to understand object
programming before you try it yourself.

Thread control
 Since the Bullet class needs to know the position of the target for collision detection, the
Target class is passed to the Bullet class as a parameter.
 Each bullet object is run in a separate Thread with its own values of position and so on.
 The various bullet threads are stopped (using return from the control loop if isAlive becomes
false) if the bullet reaches the top wall or if the bullet hits the target.
 The target thread is stopped (by setting isAlive to false) it the target is hit by a bullet.
 A new target thread is started if the user types the ‘m’ key.

Passing information between threads


The Graphics context and background colour are passed from the main program to the Bullet and
Target classes in the relevant class constructor.
Global variables for the boundary positions are passed to the Bullet and Thread classes as public
variables.
In the same way, the current position of each bullet and the target is passed back to the main class as
public variables.
A separate run() method in each class provided independent sleeping for each class.

Programming exercises
Enable the user to move the position of the gun left or right using the arrow keys.
Alternately, enable the user to change the direction of the gun by using the arrow keys.
Make the target move a little more randomly – perhaps up and down as well as left and right.
Make the game look better: include a background image and use better images for the gun and target.

Other versions of the game (available on Outlook)


Shoot1: The bullet is controlled by the ‘main’ class while the target thread is a separate class. It is
only possible to have one bullet thread at any time. However, if the user presses the space bar again
while a bullet is in motion, the class ‘remembers’ that the space bar was pressed and fires another
bullet as soon as the first bullet reaches the end of its path.
Shoot2: Here both the bullet and target are controlled by Runnable. The positions of the bullet and
target are global variables which are accessed by the two threads. It is possible in theory to start a
new bullet thread while the old one is still running, but this will reset the global variables causing the
first bullet to move strangely. Runnable is not a good way to implement this program!

Further programming exercises


A number of games were suggested in the introduction to the “Threads in Games with Animation”
notes. You can probably think of many more.

While programming these games (as well as the final result) can be fun, it can also be very
frustrating.

You need to plan what you want to do before you start!!!!

Things to think about are:


How many independent threads do you need? Once you have decided this, you can decide which of
the basic programming techniques presented in these notes you will use.

What variables need to be passed between threads and how are you going to do this? If all your
threads are part of the main program (implementing Runnable) you can start by making shared
variables global. If you need to use a separate class (extending Thread) you must carefully plan how
you pass the variables between the classes: this can get messy!

How do you do your drawing to the screen? With a single thread you would use paint(), but with
many threads it might be better to get the current graphics context and draw to this context in run().

Don’t forget the techniques presented in previous notes for preventing flicker. In particular, if your
program starts using interesting images you should use double buffering.
A Double Buffering, 120
doubleValue, 25, 38
ActionListener, 17, 60 drawImage, 20
actionPerformed, 17 drawLine, 5
add, 15 drawOval, 5
Add, 16 drawRect, 5
addActionListener, 18
addAdjustmentListener, 64
addItemListener, 62
E
addKeyListener, 65 Equality operators, 29
AdjustmentEvent, 64 Events, 18, 60
AdjustmentListener, 64 extends, 87
adjustmentValueChanged, 64 Extracting substrings, 112
Applet methods, 42
init(), 42
paint(), 42 F
Arrays, 101 fillRect, 5
Array index out of bounds error, 102 float, 27, 35
Finding The Largest (Or Smallest), 103 floatValue, 38
null pointer error, 102 Fonts, 4
Sorting An Array, 103 for loop, 33, 77
Two-Dimensional Arrays, 105 format, 25
AudioClip, 22

G
B
getAudioClip, 22
block, 35, 49 getCodeBase, 20, 22
boolean, 35, 38 getDocumentBase, 20
boolean expression, 29 getGraphics, 120
break, 73 getHeight, 21
Break, 78 getImage, 20
getKeyText, 65
C getSize, 120
getSource, 23, 31, 60
Call-By-Reference, 50 getText, 18
Call-By-Value, 50 getWidth, 21
Casting, 26, 27, 37 global declaration, 9, 35
catch, 116 Graphical User Interface, 15
char, 35, 39 Graphics Objects, 5
Character methods, 40
charAt, 113
Checkboxes, 62 I
CheckboxGroup, 63 if, 28, 29, 71
Class, 4, 83 Compound if statement, 71
Classes, 54 if .. else statements, 71
Colors, 4 if.......else, 32
compareTo, 104 if....else, 31
Components, 15 Nested if statements, 71
compound statement, 33 implement, 18
concat, 112 import, 4
concatenate, 18 Inheritance, 87
Concatenating Strings, 112 init(), 9, 42
Constructors, 54 Instance methods, 53
Continue, 78 Instance variables, 49, 53
control variable, 33 instanceOf, 60
instantiate, 12
D Instantiate, 16
Instantiating an object, 83
dangling else, 72 int, 27, 35
DecimalFormat, 25 integer variable, 8
Declare, 16, 83 Interfaces, 54
default, 73 intValue, 38
destroy(), 42 isDigit, 40, 111
double, 27, 35 isLetter, 40, 111
isLetterOrDigit, 40, 111 Parameters, 50
isLowerCase, 40, 111 parseInt, 18, 38
isSpace, 40 play, 22
isUpperCase, 40, 111 Precedence, 27
isWhiteSpace, 40 Precedence of Mathematical Operations, 36
ItemEvent, 62 private, 53, 83
ItemListener, 62 Promoting, 26, 27, 36
itemStateChanged, 62 Properties of Strings, 112
protected, 53
public, 53, 83
J
Java shortcuts, 36 R
Radio Buttons, 63
K random, 27, 37
Keyboard events, 65 Relational operators, 29
keyPressed, 65 repaint(), 42
keyReleased, 65 replace, 14, 112
keyTyped, 65 requestFocus(), 65
return, 46, 49
round, 27, 37
L run, 117
length, 14, 112 Runnable, 117
local, 35
long, 27, 35 S
loop, 23
Scope Rules, 49
Scroll bars, 64
M setBounds, 64
max, 27, 37 setLayout(null), 64
MediaTracker, 121 shortcuts, 36
method call, 48 showStatus, 18
Method Overloading, 51 sleep, 116
Methods, 42 Special characters, 111
Modularising Graphics, 52 sqrt, 27, 37
modulus, 36 start, 118
Mouse events, 66 start(), 42
mouseClicked, 67 static, 118
mouseDragged, 67 Static methods, 53
mouseEntered, 67 Static variables, 53
mouseExited, 67 stop, 23
MouseListener, 66 stop(), 42
MouseMotionListener, 67 Stopping a Thread, 118
mouseMoved, 67 String methods, 14
mousePressed, 67 Strings and Characters, 111
mouseReleased, 67 Asigning values to strings, 111
Casting, 111
Changing Strings, 112
N Comparing char with strings, 111
Comparing strings, 112
nest for loops, 77
Concatenating Strings, 112
new, 12
Extracting Strings, 112
null pointer error, 102
Properties of Strings, 112
Number Types, 27
Strings, 5
Strings, 14
O Switch statements, 72
Object, 83
object-oriented programming, 83 T
Objects, 11
this, 18
Order of precedence, 39
Threads, 115
toLowerCase, 14, 40, 111
P toString, 18, 25
toUpperCase, 14, 40, 111
Packages, 4 trim, 14, 112
paint try, 116
More on paint(), 42
paint( ), 4
paint(), 42
parameter, 44
U Variables, 8
boolean, 38
update, 68, 121 void, 44

V W
valueOf, 18 While and do loops, 78
Variable names, 35 Window Coordinates, 5
Variable types, 35 Wrapping, 54
Java Exercises

Introductory exercises
Page Ex
6 1 Hello World
7 modifications
9 2 Integer variables + modifications
12 3 Objects +modifications + teacher check
14 4 Strings
16 5 Components partially completed
19 6 Previous program added to + modification

21 7 Images

23 8_A Sound + modification


8_B modification

25 9 More strings and numbers

Practical exercises
28 10_1 sum, product, quotient and maximum value.
10_2 counts each time the user presses button and prints

29 11_1 guessing game


11_2 salaries
11_3 maximum
11_4 numbers in order
11_5 triangles

32 12_1 marks
12_2 histogram
12_3 voting
12_4 calculator

34 13_1 sum and factorial


13_2 compound interest
13_3 12 times table
13_4 prints out stars

54 16_1 areas
16_2 lines and rectangles

70 17_1 5 mouse event programs


17_2 connected straight lines
17_3 draws a line from current position of dragged mouse

73 18_1 tally of the letters, digits and spaces


18_2 include a tally of upper and lower case letters
18_3 evaluate salary of each employee for the week

80 18_4 primes
18_5 quadratics

89

107 20_1 marks


20_2 sports results a) and b)

Other programs

You might also like