You are on page 1of 62

J A V A R E F E R E N C E M A N U A L

ICS 4M

The purpose of this manual is to describe Java statements, data types, and
predefined classes and methods that are used in the grade 12 program. This
manual is not a complete guide to Java.

The examples are not complete programs. Assume that the program has been set
up correctly and all variables declared correctly.

Note to teachers: This document was prepared using Microsoft Word. It is setup
to print two pages on one piece of 8.5 x 11” paper. The order of the pages is such
that if you photocopy back to back, you should end up with a booklet in alphabetical
order.

References

Introduction to Programming in Java featuring the Ready to Program with Java


Technology IDE. J.N. Patterson Hume, Chris Step henson. Holt Software
Associates Inc. University of Toronto Press. 2000

The Java Class Libraries an Annotated Reference. Patrick Chan and Rosanna Lee,
Addison-Wesley

Thanks to Chris, Tom, and Kathy at Holt Software Associates Inc.

Linda Soulliere
Leamington District Secondary School
Java Quick Reference
What if I want to…. See

Change the size of font Font, setFont


Change the style of font Font, setFont
Display today’s date on the screen. DateFormat
Change the background as you type setTextBackgroundColor
Move the cursor to a specific location setCursor
Control layout of screen Frame, BorderLayout
Use buttons, text areas etc. in Frame, MouseListener, BorderLayout,
application programs Panel
Input data from a file BufferedReader, FileReader
Store data on disk PrintWriter, FileWriter
Find the number of words in a StringTokenizer, countTokens
sentence.
Use a counted loop for
Use a conditional loop while, do
Declare an array double, int, String
Set up a 2-dimensional array Math.random
Calculate an exponent Math.pow
Calculate the square root of a number Math.sqrt
Convert a String into an integer try
Check for integer data entry error try, catch
Stop the run of a program break
boolean

Java Data Type

Syntax boolean variableName;

Description Boolean can be a data type, expression, or constructor. It has only two
possible values, true and false.

Example ….
boolean check; // variable of type boolean

if (check)
{
c.println (“Check is true.”);
} // the lines in the if section will execute as long as check is true.

Expression

Description A Boolean expression is used in comparison situations with if or while.


The following comparison operators can be used when comparing two
numbers (not strings!)

== equal to != not equal to


<= less than or equal to < less than
>= greater than or equal to > greater than
&& and || or

Example int numberOfStudents;



if (numberOfStudents >= 25)
{
c.print (“There will not be enough computers.”);
}

while

Java Statement

Syntax while (continuation condition)


{
…statements to be executed when the condition is true
} // condition is checked before execution of commands

OR

do
{
…statements to be executed when the condition is true
} // condition is checked after the commands are executed
while (continuation condition);

Description while is used in repetition to control conditional loops. The command


lines are executed if the condition is true. Note, there is no semi-colon
(;) at the end of “while (continuation condition)” in a while loop. There is,
however, a semicolon at the end of a do-while loop.

Example …
while (value < numberOfEntries)
{
total += cost (value);
value ++;
} // find the total of the values stored in an array
/* This loop checks the condition before executing the statements. Use
do when the condition is to be checked after the statements are
executed. */

See Also do, try


BorderLayout

Java Class Library


import java.awt.*;
Class/Constructor

Syntax setLayout (new BorderLayout ());

Description BorderLayout is used to layout components on a screen and is usually


called in the Frame’s constructor or the Applet’s init method. You can
place components in any one of five positions--North, South, West,
Center, East. If you do not use one of the five positions then the other
components will expand to fill up the gap.

Example
public class MyLayout
{
public static void main (String[] args)
{
Frame design = new Frame ("Border Layout Example");
// create an instance of a frame and give it a title
design.setLayout (new BorderLayout());

// place component into frame


design.add ("North", new Button ("Quit"));
design.setSize(300,300);

// make frame and components visible


design.show();

See Also Frame, check Ready book for other layout constructors
try

Java Statement

Syntax try
{
…statements to be executed…
}
catch (exception e)
{
…statements to be executed if an exception occurs…
}

Description try is used in combination with catch to allow a program to catch and
deal with runtime errors (called exceptions in Java). The try section
contains the part of the program to be executed. The catch section
contains commands that are executed if an exception occurs. If no
exception occurs, the catch section is ignored.

Example ….
try
{
c.print (“Enter the cost of the item $”);
costStr = c.readLine();
cost = Integer.parseInt (costStr);
break;
}
catch (NumberFormatException e)
{
c.print (“Entry error has occurred.”);
}

See Also sleep example, catch, Integer.parseInt


break

Java Statement

Syntax break;

Description Use this command to “jump” out of a repetition or selection segment.

Example ….
if (input == -1)
{
break;
}
else
{
number++;
}
….
toUpperCase

Java Class Library


Included in java.lang
String class method

Syntax String toUpperCase ();

Description Returns a String where each “letter” in the string object is converted to
its upper case.

Example …
/* This sequence allows the user to enter an upper or lower case
answer. By converting the answer to upper case the programmer
avoids multiple conditions for exit from a loop. */

c.println (“Do you wish to play again? (Y/N)”);


answer = c.readLine ();
answer = answer.toUpperCase ();
if (answer.equals (“N”))
{
break;
}

See Also String, toLowerCase, break


BufferedReader

JavaClass Library
import java.io.*;
Class/Constuctor

Syntax BufferedReader (FileReader reader);

Description BufferedReader class is used to read data from a file by creating a


connection to the file to be read. The readLine method can be used on
a BufferedReader object.

Example import java.awt.*;


import java.io.*;
….
/* reading data from file can fail, therefore the need for */
/* “throws IOException” in the method declaration */

public static void main (String [] args) throws IOException


{
String fileName, line;
BufferedReader input;

// fileName is the name of the file containing data for the program.
input = new BufferedReader (new FileReader (fileName));

line = input.readLine ();

….
}

See Also PrintWriter, FileWriter, FileReader


toLowerCase

Java Class Library


Included in java.lang
String class method

Syntax String toLowerCase ();

Description Returns a String where each “letter” in the string object is converted to
its lower case equivalent.

Example …
/* This sequence allows the user to enter text. The data entered is then
converted to lower case before working with the string.*/

c.println (“Enter a line of text.”);


answer = c.readLine ();

/*all letters in answer are replaced with lower case characters*/

answer = answer.toLowerCase();

See Also String, toUpperCase


catch

Java Statement

Syntax try
{
…statements to be executed…
}
catch (exception e)
{
…statements to be executed if an exception occurs…
}

Description catch is used in combination try with to allow a program to catch and
deal with runtime errors (called exceptions in Java). The try section
contains the part of the program to be executed. The catch section
contains commands that are executed if an exception occurs. If no
exception occurs, the catch section is ignored.

Example ….
try
{
String fileName, line;
BufferedReader input;
input = new BufferedReader (new FileReader (fileName));
// where fileName contains data for the program.
line = input.readLine ();
}
catch (IOException e)
{
c.println (“File not found”);
}

See Also try, sleep example


switch

Java Statement

Description Often a programmer wants to give the user a number of options in a


menu format. In these situations where multi-way selection occurs, you
can use the switch command to avoid multi-exits from an if selection.
It makes the program “cleaner”, easier to read and debug.

Example …
int option; //declare a variable to accept user input

c.println ("Key the number of the option needed.");


c.println ("1. Start game.");
c.println ("2. Display rules.");
c.println ("3. Exit.");
//display a user menu in the run window

option = c.readInt(); //input from user

switch (option)
{
case 1:
c.println ("Great. Lets get started."); ;
break;
case 2:
c.println ("Read the rules carefully.");
break;
case 3:
c.println ("Thanks for playing.");
break;
default:
c.println ("Invalid number input.");
break;
}//decision structure used by program

See Also if
clear

HSA Class Library


import hsa.*;
Console class method

Syntax c.clear();

Description Clears a Console window and places the cursor in the top left corner of
the screen.

See Also setCursor


StringTokenizer

Java Class Library


import java.util.*;
Class/Constructor

Syntax StringTokenizer (String str)

Description Creates a StringTokenizer object to breakdown a string into tokens


separated by white space. It can be used to count the number of
tokens (“words”) in a line or find the next token.

Example …
// declare identifiers
String answer;
int value;
String group []; // an array of String variables

// enter group member names


c.println ("Key in each member of the group on this line.");
answer = c.readLine ();

// set up StringTokenizer and set value to number of members


StringTokenizer members = new StringTokenizer (answer);
value = members.countTokens();

// Create an array of the appropriate size.


group = new String [value];
for (int j = 0 ; j < value ; j++)
{
group [j] = members.nextToken ();

} // initialize a group array to group names


….

See Also countTokens, nextToken, hasMoreTokens


compareTo

Java Class Library


Included in java.lang
String class method

Syntax int compareTo (String str)

Description This method is used to compare two strings. The method returns a
negative value if the String object used to call compareTo is less than
the String argument passed to compareTo. If the String object is
greater than the argument, compareTo returns a positive value, and it
returns 0 if the two Strings are identical.

Example String answer;



c.println (“What is your last name?”);
answer = c.readLine();

if (answer.compareTo (“N”) > 0)


{
c.println (“I like winter best too.”);
}
else
{
c.println (“My favourite season is winter.”);
}

See Also String, equals, toUpperCase, toLowerCase


String

Java Class Library


Included in java.lang
Class

Syntax String str;

Description This data type class is used for alphanumeric data such as names and
addresses. Always use variable names that are self-explanatory and in
camel style. You will find that str is often used as a variable name for a
string variable.

Example String lastName; mailingAddress;


….

See Also StringTokenizer, toLowerCase, toUpperCase, equals, compareTo


countTokens

Java Class Library


import java.util.*;
StringTokenizer class method

Syntax int countTokens();

Description This method will count the number of tokens (“words”) in a


StringTokenizer. The tokens are separated by spaces.

Example …
String lineOfPoem; // to store the input data

lineOfPoem = c.readLine();

// create a StringTokenizer object


StringTokenizer poem = new StringTokenizer (lineOfPoem);

// display the number of words in the line of data entered


c.println (“The line has “ + poem.countTokens () + “ words”);

See Also StringTokenizer, hasMoreTokens, nextToken


sleep

Java Class Library


Included in java.lang
Thread class method

Syntax Thread.sleep (int milliseconds);

Description The sleep method in the Thread constructor interrupts the execution of
the current thread that is running.

Example /*
Method to cause a delay (sleep) in the program. For example:
delay (100) will call the program and delay execution for 100
milliseconds.
*/
public static void delay (int milliseconds)
{
try
{
Thread.sleep (milliseconds);
}
catch (InterruptedException e)
{
;
}
}

See Also catch, try, Thread


DateFormat

Java Class Library


import java.util.*;
import java.text.*;
Class

Syntax DateFormat.getDateInstance (int style);


DateFormat.getTimeInstance (int style);
DateFormat.getDateTimeInstance (int style);

Description Use to get the date and/or time in integer format according to the style
required. This value can then be changed to a string so that you can
display a date and/or time on the screen.

Date in full format: Monday, July 15, 2002


Date in long format: July 15, 2002
Date in medium format: 15-Jul-02
Date in short format: 7/15/02
The program will default to medium format.

Example // retrieve the long form of the date


DateFormat today = DateFormat.getDateInstance (DateFormat.LONG);

// convert integer form to string format and display


c.println (today.format (new Date ()));
show

Java Class Library


import java.awt.*;
Frame class method

Syntax show ();

Description After a frame is set up, then it is necessary to make the components
visible. The command show() may be used or setVisible()

Example import java.awt.*;

public class LayoutExample


{
public static void main (String[] args)
{
Frame design = new Frame ("Border Layout Example");
// Create an instance of a frame and give it a title
design.setLayout (new BorderLayout());
design.add ("North", new Button ("Quit"));
design.setSize (300,300);

// make the frame and components visible


design.show();

See Also Frame, pack


do

Java Statement

Syntax do

Description do is used in repetition sequences to control conditional loops. The


command lines are executed if the condition shown at the end of the
loop is true. Note, there is no semi-colon (;) after do

Example …
do
{
total += cost [value];
value ++;
}
while (value < numberOfEntries);

// loop to find the total of the values stored in an array


/*This loop checks the condition after executing the statements. */
….

See Also while


setTextBackgroundColor

HSA Class Library


import hsa.*;
Console class method

Syntax setTextBackgroundColor (Color c);

Description This command is handy when you have created your own “button” for
input. Use this method so that the background of the button is the
same as your screen background.

Example …
int mainNumber;
// blackground colour to pink and draw background
c.setColor (new Color (214, 115, 152));
c.fillRect (0, 0, c.getWidth (), c.getHeight ());

c.setColor (Color black);


c.drawString ("Please enter the number here:", 0, 420);

// draw a white box with a black outline


c.setColor (Color.white);
c.fillRect (200, 406, 50, 18);
c.setColor (Color.black); // set outline colour to black
c.drawRect (200, 406, 50, 18);

c.setTextBackgroundColor (new Color (214, 115, 152));


// set print background colour to pink
c.setCursor (25, 26);

mainNumber = c.readInt ();


// enter value into “button”
….

See Also setColor


double, double[]

Data type

Syntax double variableName;


// declare a variable to be real

double variableName [] = new double [arraySize];


// declare an array of real numbers with arraySize elements

Description Float and double are both primitive data types used for real numbers.
Double requires twice the amount of bits. An integer can be made into
a real value by using the double command (casting).

Example …
double firstNumber = 32.34;
int secondNumber = 15;

c.println (firstNumber, 6, 2);

// display the integer number as a real number


c.println ((double) secondNumber, 6, 2);

/*the first value after the variable name indicated the field width to be
used to display the real number. The second value is the number of
decimal places required.*/

See Also int, String


setSize

Java Class Library


import java.awt.*;
Frame class method

Syntax setSize (int width, int height);

Description Change the size of the frame to the width and height specified in pixels.
The method can be used within a frame created by the user.

Example public class MyLayout


{
public static void main (String[] args)
{
Frame design = new Frame ("Border Layout Example");
// create an instance of a frame and give it a title
design.setLayout (new BorderLayout());

// place component into frame


design.add ("North", new Button ("Quit"));
design.setSize (300,300);

// make frame and components visible


design.show();

See Also Frame, BorderLayout


drawArc, fillArc

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax drawArc (int x, int y, int width, int height, int startAngle, int arcAngle);
fillArc (int x, int y, int width, int height, int startAngle, int arcAngle);

Description Draws an arc in an invisible box starting at position (x, y) with indicated
width and height. The starting angle is based on the unit circle in
standard position. The last integer indicates the number of degrees in
the arc. The arc is drawn counter clockwise. To draw a clockwise angle
use a negative value for the arcAngle.

(x, y) width
90

height
180 0

270
Example …
// set color to blue and draw first face
c.setColor (Color.blue);
c.drawOval (10, 25, 60, 60);
// set color to red and draw second face and mouths
c.setColor (Color.red);
c.drawOval (100, 25, 60, 60);
c.drawArc (20, 60, 40, 40, 30, 120);
c.drawArc (110, 35, 40, 40, 330, - 120);
// set color to black and draw eye for both faces
c.setColor (Color.black);
c.fillOval (25, 40, 5, 5);
c.fillOval (50, 40, 5, 5);
c.fillOval (115, 40, 5, 5);
c.fillOval (140, 40, 5, 5);

or

public void paint (Graphics g)


{
g.setColor (Color.red);
g.fillArc (50, 150, 50, 50, 45, 90) // Draw an arc from 45-135

See Also drawRect, drawOval


setFont

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax setFont (Font fnt);

Description The method sets the font of the graphics context. It is used with
drawString. The font objects must be declared before using setFont.

Example // create instances of fonts needed for program


Font font1 = new Font ("Serif",Font.BOLD,72);
Font font2 = new Font ("Impact",Font.PLAIN,45);

c.setColor (Color.blue); // sets text color to blue

c.setFont (font1); // sets font to serif, bold, size 75

// places Hello on screen with the color and font as indicated


c.drawString ("Hello",100,330);

c.setFont (font2); // sets font to impact, plain, size 45

// display literal according to font and color


c.drawString ("Grade 12",100,370);

or

// Draw a giant “Hello!”


public void paint (Graphics g)
{
Font bigFont = new Font ("Serif",Font.BOLD,72);
g.setFont (bigFont);
g.drawString (50, 150, “Hello!”);

See Also Font


drawImage

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax drawImage (Image img, int x, int y, ImageObserver observer);

Description Draws an image on the screen. The top left hand of the image is at the
(x, y) location. The image must first be declared and then get the
image with the getImage method.

Example import java.applet.*;


import java.awt.*;

public class LoadAppletImage extends Applet


{
Image img;

public void init ()


{
img = getImage (getDocumentBase (), "house.gif");
} // init method

public void paint (Graphics g)


{
g.drawImage (img, 0, 0, null);
} // paint method
} // LoadImage class

See Also Image, getImage, getDocumentBase


setCursor

HSA Class Library


import hsa.*;
Console class method

Syntax c.setCursor (int row, int col);

Description Places the cursor position to row and column indicated in the brackets.
Note that this is a row and column position not a pixel (x, y) position.

Example …
// move cursor to (row, column)
c.setCursor (15, 25);
c.print (“Start postion”);

c.setColor (Color.red);
// start rectangle in pixel (x, y) position
c.drawRect (15, 25, 50, 50);
….
See Also setCursorVisible, setTextBackgroundColor, setTextColor
drawOval, fillOval

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax drawOval (int x, int y, int width, int height);

fillOval (int x, int y, int width, int height);

Description Places an ellipse in an invisible box on the screen. The top left of the
box starts at position (x, y). The box has a width and height as
indicated by the last two parameters. The centre of the box is found at
((x + width/2), (y + height/2).

(x, y) width

height

Example c.setColor (Color green);


c.drawOval (0, 0, 10, 25);
/*places an oval in the top left corner of the monitor. The inscribed oval
is in a box of 10 pixels by 25 pixels*/

c.setColor (Color pink);


c.fillOval (100, 0, 10, 25);
// places a filled oval at the top of the screen, 100 pixels from the left.

See Also drawRect, drawArc


setColor

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax c.setColor (Color c);


c.setColor (new Color (int red, int green, int blue));

Description Changes the text color. You can use a predefined color such as red,
blue, green, gray, yellow, cyan, darkGray, lightGray, magenta, orange,
pink, white. You may also define your own color by using the second
option. For the correct integer combinations of red, green, blue see
http://mattkelli.com/programming/java/colors/colors.html

Example …
c.setColor (Color.red);
// start rectangle in pixel (x, y) position with width and height of 50
c.drawRect (15, 25, 50, 50);

// change color using the R, G, B hexadecimal code


c.setColor (new Color(214, 115, 152));

// draw second rectangle in new color


c.drawRect (30, 30, 50, 50);
….

See Also setTextBackgroundColor, setTextColor


drawRect, fillRect

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax drawRect (int x, int y, int width, int height);

fillRect (int x, int y, int width, int height);

Description Places a box on the screen. The top left of the box starts at position
(x, y). The box has a width and height as indicated by the last two
parameters. The centre of the box is found at ((x + width/2),
(y + height/2).

Example c.setColor (Color blue);


c.drawRect (0, 0, 10, 25);
/*places the outline of a blue rectangle in the top left corner of the
monitor with a width of 10 pixels and a height of 25 pixels*/

c.setColor (Color red);


c.fillRect (100, 0, 10, 25);
/*places a red rectangle at the top of the screen, 100 pixels from the
left.

See Also drawOval, drawArc


setBackground

Java Class Library


import java.awt.*;
Component Class

Syntax setBackground (Color c);

Description setBackground is used to place a color in the background of a


component. The method works in both applets and applications. The
setBackground command does not work with the Console class but will
work with a Frame component.

Example /*this is a modified version of a section of the example in Frame.*/

public class FrameExample extends Frame


{
TextField nameItem, ageItem;
Label name, age;
Button quitButton;
// list components

// Constructor
public FrameExample ()
{
super ("Registration"); // Set the frame's name
// setup components to be placed in frame

Panel dataScreen = new Panel ();


dataScreen.setBackground (Color.pink);

quitButton = new Button ("Quit");


quitButton.setBackground (Color.green);
…..

See Also getBackground, setTextBackground


drawString

HSA Class Library and Java Class Library


import hsa.*; or import java.awt.*;
Console class or Graphics class method

Syntax drawString (String str, int x, int y)

Description Places a string starting at position (x, y). The words may be enclosed
in quotations or may be referred to by a variable name. Font and color
changes are made prior to placing the string on the screen.

Example String name;


Font font1 = new Font ("Serif",Font.BOLD,72);
Font font2 = new Font ("Impact",Font.PLAIN,45);
// instantiate fonts to be used

c.println ("Enter your name.");
name = c.readLine();

setColor (Color.blue);
c.setFont (font1);
c.drawString ("Hello",100,330); // draw a literal on screen
c.setFont (font2);
c.drawString (name,100,370); // draw a string variable

See Also Font, setFont


readLine

HSA Class Library or Java Class Library


import hsa.*; or import java.io.*;
Console Class or BufferedReader class method

Syntax String c.readLine ();

Description readLine is used to input text from the keyboard and from file. To use
readLine to input text from file, you must create a connection (stream)
from the file to the program using BufferedReader and FileReader.
See the Ready text for more examples of these commands.

If there is no more text in a file to be read, then readLine returns null.

Example …….
String firstLine, poet;
// first setup the string objects required
….
c.print (“Enter the first line of the poem.”);
firstLine = c.readLine();
// data inputted from the keyboard

c.print (“What is the poet’s name?”);


poet = c.readLine();
…..

See Also readInt, readDouble, BufferedReader, FileReader


equals

Java Class Library


Included in java.lang
String class method

Syntax boolean equals(String str);

Description Returns true if the String object is equal to str. You cannot use <, >, ==
to compare strings. It is necessary to use the equals method of the
String class for strings of equal value. To compare strings for greater
than or less than value use compareTo.

Example String answer;



c.println (“What is your favourite season?”);
answer = c.readLine();

if (answer.equals (“Summer”))
{
c.println (“See you at the marina.”);
}
else
{
c.println (“See you at school.”);
}

See Also String, compareTo, toUpperCase, toLowerCase


readInt

HSA Class Library


import hsa.*;
Console class method

Syntax c.readInt ();

Description The readInt method is used to input integers from the keyboard. Note
that in order to read integers from a file, you first read in the data using
readLine() then convert the data to an integer (Integer.parseInt).

Example int age, phone;


String phoneStr;
…….
c.println (“How old are you?”);
age = c.readInt();
// the value keyed in will be stored in age
…….
// key in a number as a string location and convert to an integer
c.println (“What is your phone number?”);
phoneStr = c.readLine();
phone = Integer.parseInt (phoneStr);
….

See Also readLine, readDouble, Integer.parseInt


FileReader

Java Class Library


import java.io.*;
Class/Constructor

Syntax FileReader (String fileName) throws FileNotFoundException

Description FileReader is used when the programmer wishes to input data from a
file in application programs. FileReader creates an object for the
fileName. The object is then used with BufferedReader.

Example import java.awt.*;


import java.io.*;
….

/* Reading data from file can fail, therefore the need for
“throws IOException” in the declaration of main */
public static void main (String [] args) throws IOException
{
String fileName, line;
BufferedReader input;
input = new BufferedReader (new FileReader (fileName));
// where fileName contains data for the program.

line = input.readLine ();


while (line != null)
{
c.println (“Read “ + line + “ from the file.”);
line = input.readLine ();
}
….
}

See Also BufferedReader, catch (for example of finding the IOException)


readDouble

HSA Class Library


import hsa.*;
Console class method

Syntax c.readDouble ();

Description readDouble is used to input real numbers using the keyboard.

Example ….
double price;
….
c.print (“What is the cost of the item?”);
price = c.readDouble();
// the value keyed in will be stored in price.
…..

See Also readLine, readInt


FileWriter

Java Class Library


import java.io.*;
Class/Constructor

Syntax FileWriter (String fileName) throws IOException;

Description FileWriter is used when the programmer wishes to output data to a file
in application programs. FileWriter creates an object for the fileName.
The object is then used with PrintWriter.

If the data will be read into the program later then the file must be
closed. Use the close method of the PrintWriter class.

Example ….
PrintWriter names;
String lastName;

names = new PrintWriter (new FileWriter ("Students"));


/*The file “Students” will save the words inputted by the user.*/

for (int j = 0 ; j < 10 ; j++)


{
c.print ("What is the student's last name?");
lastName = c.readLine ();
names.println (lastName);
}/*loop to allow the user to enter 10 last names. The names are then
printed to file.*/

names.close ();
/*file is closed it it is to be used as input before the end of the program*/
….

See Also PrintWriter, FileReader, BufferedReader


PrintWriter

Java Class Library


import java.io.*;
Class/Constructor

Syntax PrintWriter (FileWriter writer)

Description PrintWriter works with FileWriter so that data can be saved to file.
PrintWriter actually writes the ASCII data to file. The methods of this
class are print and close.

Example …
PrintWriter wordList;
String words;
int value;
….
wordList = new PrintWriter (new FileWriter ("Hangman List"));
/*The file “Hangman List” will save the words to be use in the game.*/

c.println (“How many words are to be in the list?”);


value = c.readInt ();

for (int j = 0; j < value; j++)


{
c.println (“Enter a word.”);
words = c.readString();
wordList.println (words);
}/*loop to allow the user to enter words to a word list. The words are
then printed to file.*/

wordList.close ();
/*file is closed if it is to be used as input before the end of the program*/
….

See Also FileWriter, BufferedReader, FileReader


Font

Java Class Library


import java.awt.*
Constructor

Syntax Font (String name, int style, int size);

Description Constructs a new Font instance. Two steps are needed to set up a font
change in the program. First, create an instance of the Font. The
styles available are Font.PLAIN, Font.BOLD, Font.ITALIC. Second, you
set the font just prior to use. This step works the same as the setColor
method. Once the font is set, it stays in place until a new font is set.

Example String name;


Font font1 = new Font ("Serif",Font.BOLD,72);
Font font2 = new Font ("Impact",Font.PLAIN,45);

c.println ("Enter your name.");
name = c.readLine();

setColor (Color.blue);
c.setFont (font1);
c.drawString ("Hello",100,330); // draw a literal on screen
c.setFont (font2);
c.drawString (name,100,370); // draw a string variable

See Also setFont, setColor


print, println

HSA Class Library


import hsa.*;
Console class method

Syntax c.print (literal);


c.print (variableName);
c.print (variableName, int fieldSize);
c.print (variableName, int fieldSize, int decimalPlaces);

c.println (literal);
c.println (variableName);
c.println (variableName, int fieldSize);
c.println (variableName, int fieldSize, int decimalPlaces);

Description The print methods are used to display information in the run window.
After the print method, the cursor remains on the same line, just after
the displayed item. After the println method, the cursor moves down to
the next line (causing the window to scroll if necessary).

Example ….
String name;
double cost;
….
c.print (name); // the string data stored in name is displayed

c.println (cost, 10, 2) ;


/*amount owing will take up 10 spaces on the screen and will be shown
rounded to two decimal places.*/

c.print (“Thank you for shopping here.”);


// The text (literal) between the quotation marks is displayed
for

Java Statement

Syntax for (int startValue ; startValue < endValue ; increments)

Description This command is used to set up a counted loop for a repetition


sequence. Note, there is no semi-colon at the end of the line.
Use brace brackets around the sequence of commands to be executed
in the loop.

Example int [ ] mark = new int [10] // declare an array of integers


….
for (int j = 0 ; j<10 ; j++)
{
mark [counter] = 0
} // loop to initialize all parts of the array to 0

See Also while, do


Panel

Java Class Library


import java.awt.*;
Constructor

Description Panel allows the user to nest a layout within another layout. Panels
may be used both in applets and applications that extend the Frame
class. Plan your design for the run screen on paper first.

Example import java.awt.*;

public class PanelExample extends Frame


{
// The fields of the class
TextArea comment;
TextField presentationItem;
Label remarks, presentation;
Panel commentSection, presentationSection;

// Constructor
public PanelExample ()
{
super ("Evaluation Form");
// Create top panel and assign it a layout
presentationSection = new Panel();
presentationSection.setLayout (new BorderLayout());
// Create bottom panel and assign it a layout
commentSection = new Panel();
commentSection.setLayout (new BorderLayout());
// Create Label and TextField to place in the top panel
presentation = new Label ("What presentation did you attend?");
presentationItem = new TextField (25);
// Place the items in the top panel
presentationSection.add ("North", presentationItem);
presentationSection.add ("South", presentation);
// Create Label and TextField to place in the bottom panel
remarks = new Label ("Please comment on the presentation.");
comment = new TextArea (12, 15);
// Place the components in the bottom panel
commentSection.add ("North", remarks);
commentSection.add ("South", comment);
// Place the two panels into the
add ("North", presentationSection);
add ("South", commentSection);

See Also Frame, BorderLayout
Frame

Java Class Library


import java.awt.*
Class/Constructor

Description The Frame class is used in applications in order to produce to a


window. In general, a Frame is used by creating a new class which
extends the Frame class. The class’ constructor is used to layout the
run window. A frame is a window with additional properties: a title bar,
a menu bar, a border, a cursor, and an icon image. The example below
shows the beginning stages of setting up a registration form using the
Frame Application Boilerplate

Example …
public class FrameExample extends Frame
{
TextField nameItem, ageItem; // ”boxes" for data entry
Label name, age; // labels for boxes
Button quitButton;

// FrameExample’s constructor
public FrameExample ()
{
super ("Registration"); // Set the frame's name

// setup components to be placed in frame


Panel dataScreen = new Panel ();
quitButton = new Button ("Quit");
nameItem = new TextField (20);
ageItem = new TextField (3);
name = new Label ("Enter your name.");
age = new Label ("What is your age?");

// Add components to the panel


dataScreen.add (name);
dataScreen.add (nameItem);
dataScreen.add (age);
dataScreen.add (ageItem);
dataScreen.add (quitButton);

// Add panel to the window


add ("North", dataScreen);
setSize (600, 400); // Set the frame's size
show (); // Show the frame
} // Constructor
pack

Java Class Library


import java.awt.*;
Frame class method

Syntax pack ();

Description Used to resize a Frame to the minimum size needed to include all the
components.

Example import java.awt.*;

public class Layout


{
public static void main (String[] args)
{
Frame design = new Frame ("Border Layout Example");
// create an instance of a frame and give it a title
design.setLayout (new BorderLayout());
design.add ("North", new Button ("Quit"));
design.add (“East”, new Button (“Start”));
design.pack();
design.show();

See Also Frame, show


Frame (continued)

// The system calls this method when the user clicks a button.
public boolean action (Event e, Object arg)
{
if (e.target == quitButton)
{
hide ();
System.exit (0);
}
else
{
return false;
}
return true;
}

// The main method must appear in order for this class to


// be an application.
public static void main (String [] args)
{
new FrameExample (); // Create a FrameExample frame
} // main method
} // FrameExample class

See Also Border Layout for second Frame example


nextToken

Java Class Library


import java.util.*;
StringTokenizer class method

Syntax String nextToken ();

Description This method will find the next token (“word”) in a StringTokenizer.
Remember the StringTokenizer is a line read from file or keyed into the
computer.

Example …..
String lineOfPoem;
int numberOfWords;

// key in line and instantiate a StringTokenizer


lineOfPoem = c.readLine();
StringTokenizer poem = new StringTokenizer (lineOfPoem);

// calculate and display the number of words in the line


numberOfWords = poem.countTokens();
c.println (“The line has “+poem.countTokens()+ “ words”);

// loop to display each word of the line on a separate line


for (int j = 1; j <= numberOfWords; j ++)
{
c.println (“Word “ + j + “ of the line is “+ poem.nextToken());
}
….

See Also StringTokenizer, hasMoreTokens, countTokens


getBackground

Java Class Library


import java.awt.*;
Component class method

Syntax Color getBackground ();

Description Retrieves the component’s background color and is most often used
with an applet with animation to ensure that the background matches
that of a browser. Different browsers may run with different background
colors or different shades of the same color. Using getBackground is
easier than matching. getBackground can also be used in an
application that extends Frame.

Example import java.applet.*;


import java.awt.*;

public class CrossCircle extends Applet


{
public void paint (Graphics g)
{
Color bg = getBackground ();
g.setColor (Color.red);
g.fillOval (50, 50, 100, 100);
g.setColor (bg);
g.fillRect (85, 0, 115, 200);
g.fillRect (0, 85, 200, 115);
} // paint method
} // CrossCircle class

See Also setBackground, setTextBackgroundColor


MouseListener

Java Class Library


import java.awt.*;
import java.awt.event.*;
Interface

Description Both an Applet and an application program using a Frame can be setup
to use a mouse. Note: you cannot use MouseListener with the HSA
console. In applications, you must extend a Frame and implement the
MouseListener methods. In an Applet, you must extend the Applet and
implement the MouseListener methods. Finally, you must add the
MouseListener in the constructor (for a Frame) or the init method (for
an Applet)

Example import java.awt.*;


import java.awt.event.*;

public class Mouse extends Frame implements MouseListener


{
boolean drawCircle = false;

// Constructor
public Mouse ()
{
setSize (300, 300);
show ();
addMouseListener (this);
} // Constructor

// Called by the system when redrawing the window or


// when the repaint method is called.
public void paint (Graphics g)
{
if (drawCircle)
{
g.setColor (Color.blue);
g.drawString ("Thank you!", 10, 150);
g.drawRect (50, 50, 25, 35);
}
else
{
g.setColor (Color.red);
g.drawString ("Click in the rectangle", 10, 150);
g.drawOval (50, 150, 12, 12);
}
} // paint method
getDocumentBase

Java Class Library


import java.applet.*;
Applet class method

Syntax URL getDocumentBase ();

Description Returns the URL of the directory containing the HTML document which
launched the Applet. This is commonly used as an argument to
getImage to load images located in the same directory as the HTML
file.

Example import java.applet.*;


import java.awt.*;

public class LoadAppletImage extends Applet


{
Image img;

public void init ()


{
img = getImage (getDocumentBase (), "house.gif");
} // init method

public void paint (Graphics g)


{
g.drawImage (img, 0, 0, null);
} // paint method
} // LoadImage class

See Also getImage, drawImage


MouseListener (continued)

// Called by the system when the user clicks the mouse.


public void mouseClicked (MouseEvent event)
{
int x, y; // x, y represent coordinates in the xy plane
x = event.getX (); // current x location
y = event.getY (); // current y location

// If the mouse click occurred in the rectangle


if (x > 50 && x < 75 && y > 50 && y < 85)
{
drawCircle = true;
// Cause paint to be called again, which this time draws an oval.
repaint ();
} // draw a red oval when the user clicks the rectangle
}// detects activity when mouse is clicked

// We do not use the rest of the Mouse events available,


// but they must be included here.
public void mousePressed (MouseEvent event)
{
}

public void mouseReleased (MouseEvent event)


{
}

public void mouseEntered (MouseEvent event)


{
}

public void mouseExited (MouseEvent event)


{
}

// The main method that is run when Mouse.class is executed.


public static void main (String [] args)
{
// Create a new Mouse Frame
new Mouse();
} // maint method
} // Mouse class

See Also Frame


getHeight

HSA Class Library


import hsa.Console
Console class method

Syntax c.getHeight();

Description Returns the height of the drawing surface of the Console window in
pixels. If you are using an Applet or a Frame use the getSize().height
method.

Example …
// draw a red circle in the centre of the screen.
c.setColor (Color.red);
c.fillOval (c.getWidth() / 2 - 50, c.getHeight() / 2 - 50, 100, 100);
/*use getWidth and getHeight to find the size of the screen, divide by 2
and subtract the radius of the circle to centre*/
….

See Also getWidth


Math.sqrt

Java Class Library


part of java.lang
Math class method

Syntax double Math.sqrt (double a)

Description This method of the Math class returns the square root of a number.

Example ….
double sideC;
double sideA = 15;
double sideB = 14;
// variables for three sides of a triangle, where sideC is the hypotenuse
….
sideC = Math.sqrt (Math.pow (sideA, 2) + Math.pow (sideB , 2));
// find the length of the hypotenuse using Pythagorean Theorem

See Also Math.random, Math.pow


getImage

Java Class Library


import java.applet.*; or import java.awt.*;
Applet class or Toolkit class method

Syntax Image getImage (URL directoryAddr, String filename);


or
Image getToolkit ().getImage (String pathname);

Description Creates an image object and loads a GIF or JPG image into it. Can
return before the image is completely loaded, in which case the image
might not be drawn instantly when drawImage is used.

Example import java.awt.*;

public class LoadFrameImage extends Frame


{
Image img;

// Constructor loads the picture, sets the Frame’s size and


// makes the Frame appear.
public LoadFrameImage ()
{
img = getToolkit ().getImage ("house.gif");
System.out.println (img);
setSize (300, 300);
show ();
} // constructor

// Called when the Frame needs to be repainted.


public void paint (Graphics g)
{
g.drawImage (img, 50, 50, null);
} // paint method

// The main method called when the program is executed. Creates


// a single copy of the LoadFrameImage window.
public static void main (String [] args)
{
new LoadFrameImage ();
}
} // LoadImage class

See Also drawImage, getDocumentBase


Math.random

Java Class Library


Included in java.lang
Math class method

Syntax double Math.random()

Description The Math.random() method is used to generate random values. The


command Math.random() returns a random number between 0.0
(inclusive) and 1.0 (exclusive).

Example …
/*The following sequence will generate a set of random marks for a
class of students. The range of marks will be from 1 to 100*/
int numberOfStudents, numberOfTests;
c.println ("How many students are in the class?");
numberOfStudents = c.readInt ();
c.println ("How many tests have been written?");
numberOfTests = c.readInt ();

int marks [] [] = new int [numberOfTests] [numberOfStudents];


// set up two dimensional array

for (int k = 0 ; k < numberOfTests ; k++)


{
c.println ("Test " + (k + 1) + "");
for (int j = 0 ; j < numberOfStudents ; j++)
{
marks [k] [j] = (int) (Math.random () * 100) + 1;
c.println (marks [k] [j], 7);
}
}

See Also Math.pow, Math.sqrt


getWidth

HSA Class Library


import hsa.*;
Console class method

Syntax c.getWidth ();

Description Returns the width of the drawing surface of the Console window in
pixels. If you are using an applet or a frame use the getSize().width
method.

Example ….
// draw a green circle in the top right corner of the screen
c.setColor (Color.green);

c.fillOval (c.getWidth () - 100, 0, 100, 100);


/*subtract the width of the circle from the width of the screen so that all
the circle is displayed*/
….

See Also getHeight


Math.pow

Java Class Library


part of java.lang
Math class method

Syntax double Math.pow (double x, double y)

Description This method is used to evaluate powers. x is the base of the power; y
is the exponent.

Example ….
/*create a chart indicating the decimal value of binary place values*/
int places;
c.println ("How many place values are needed?");
places = c.readInt ();
c.clear ();

for (int j = places ; j >0 ; j--)


{
c.print (Math.pow (2, j), 5);
c.print (" |");
}
c.println (" 1");
….

See Also Math.random, Math.sqrt


hasMoreTokens

Java Class Library


import java.util.*;
StringTokenizer class method

Syntax boolean hasMoreTokens();

Description This method will look to see if there is another token (“word”) in a
StringTokenizer. It is often used to check for the end of a line.

Example …..
String lineOfPoem;
int numberOfWords;

lineOfPoem = c.readLine();
StringTokenizer poem = new StringTokenizer (lineOfPoem);

numberOfWords = poem.c ountTokens();


c.println (“The line has “+poem.countTokens()+ “ words”);

while (poem.hasMoreTokens())
{
c.println (“The next word is “ + poem.nextToken() +”.”):
}

See Also StringTokenizer, hasMoreTokens, countTokens


Image

Java Class Library


import java.awt.*;
Class

Syntax Image

Description The Image class is used to create objects representing images loaded
from GIF or JPEG files. Image objects are not created using new, but
returned from the getImage method. The Image object can then be
passed to drawImage. Because an Image object can be incomplete,
when loading over the net on a slow connection, you can occasionally
see drawImage drawing the image piece by piece as the image is
loaded.

Example import java.awt.*;

public class LoadFrameImage extends Frame


{
Image img;

// Constructor loads the picture, sets the Frame’s size and


// makes the Frame appear.
public LoadFrameImage ()
{
img = getToolkit ().getImage ("house.gif");
System.out.println (img);
setSize (300, 300);
show ();
} // constructor

// Called when the Frame needs to be repainted.


public void paint (Graphics g)
{
g.drawImage (img, 50, 50, null);
} // paint method

// The main method called when the program is executed. Creates


// a single copy of the LoadFrameImage window.
public static void main (String [] args)
{
new LoadFrameImage ();
}
} // LoadImage class

See Also getImage, drawImage, getDocumentBase


if

Java Statement

Syntax if (condition)
{
…..statements executed if true;
}
else
{
….statements executed if false;
}

Description if is used for selection. Note that the switch command is another form
of selection. See text for further information. For numbers use ==, !=,
>, >=, <, <= in the condition. For strings, use methods of the String
class for the comparison. An else if section may be nested in the if
sequence.

Example ….
if (cost > 4.00)
{
c.println (“Both GST and PST are charged.”);
}
else
{
c.println (“No taxes added.”);
}
….
See Also equals, compareTo
int, int[]

data type

Syntax int variableName; // declare a variable of integer type

int arrayName [] = new int [arraySize];


// declare an array of integers with arraySize elements

Description int is a primitive data type. It is used for integer data. Integers require
less memory than double values (4 bytes vs. 8 bytes). Use integers
unless decimal places are required.

Example ….
int size;
// size will store the number of elements in the array

c.print ("How many values are to be stored? ");


size = c.readInt ();

int number [] = new int [size];


// declare an array of integers

for (int j = 1 ; j <= size ; j++)


{
c.print ("Enter value " + j + " ");
number [j - 1] = c.readInt ();
} // prompts user for values and stores in the array
….

See Also double, String, Math.random (for 2-dimensional array)