Java Reference Manual: Ics 4M
Java Reference Manual: Ics 4M
Java Reference Manual: Ics 4M
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
The Java Class Libraries an Annotated Reference. Patrick Chan and Rosanna Lee,
Addison-Wesley
Linda Soulliere
Leamington District Secondary School
Java Quick Reference
What if I want to…. See
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
Java Statement
OR
do
{
…statements to be executed when the condition is true
} // condition is checked after the commands are executed
while (continuation condition);
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. */
…
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());
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.”);
}
Java Statement
Syntax break;
Example ….
if (input == -1)
{
break;
}
else
{
number++;
}
….
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. */
JavaClass Library
import java.io.*;
Class/Constuctor
// fileName is the name of the file containing data for the program.
input = new BufferedReader (new FileReader (fileName));
….
}
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.*/
answer = answer.toLowerCase();
…
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”);
}
…
Java Statement
Example …
int option; //declare a variable to accept user input
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
Syntax c.clear();
Description Clears a Console window and places the cursor in the top left corner of
the screen.
Example …
// declare identifiers
String answer;
int value;
String group []; // an array of String variables
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.
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 lineOfPoem; // to store the input data
lineOfPoem = c.readLine();
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)
{
;
}
}
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.
Description After a frame is set up, then it is necessary to make the components
visible. The command show() may be used or setVisible()
Java Statement
Syntax do
Example …
do
{
total += cost [value];
value ++;
}
while (value < numberOfEntries);
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 ());
Data type
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;
/*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.*/
…
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.
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
Description The method sets the font of the graphics context. It is used with
drawString. The font objects must be declared before using setFont.
or
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.
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
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
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);
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).
// Constructor
public FrameExample ()
{
super ("Registration"); // Set the frame's name
// setup components to be placed in frame
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.
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
…
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.
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
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.
if (answer.equals (“Summer”))
{
c.println (“See you at the marina.”);
}
else
{
c.println (“See you at school.”);
}
…
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).
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.
/* 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.
Example ….
double price;
….
c.print (“What is the cost of the item?”);
price = c.readDouble();
// the value keyed in will be stored in price.
…..
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.close ();
/*file is closed it it is to be used as input before the end of the program*/
….
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.*/
wordList.close ();
/*file is closed if it is to be used as input before the end of the program*/
….
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.
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
…
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
Java Statement
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.
// 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
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
Description Used to resize a Frame to the minimum size needed to include all the
components.
// 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;
}
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;
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.
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)
// Constructor
public Mouse ()
{
setSize (300, 300);
show ();
addMouseListener (this);
} // Constructor
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.
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*/
….
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
…
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 …
/*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 ();
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);
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 ();
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);
while (poem.hasMoreTokens())
{
c.println (“The next word is “ + poem.nextToken() +”.”):
}
…
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.
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
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