3.
Loop body execution.
4.
Post-statement are executed.
5.
Back to step 2 through 4 until the stop condition is false, then loop exits.
Another example of
for
loop is the program that prints out the results of multiplications from 1 to

12.
class MultiplicationTable{
public static void main(String[] args){
for(int i = 1; i <= 12; i++){
for(int j = 1; j <= 12; j++){
Java Lab Manual by Yasser Jaffal (2008)

43
int k = i * j;
System.out.println(i + " * " + j + " = " + k);
}
}
}
}
In the above example, we used
nested
loops, that is, a loop inside the body of another loop, we can

use as many levels of nesting as we need. Be ware that when we use nested loops, the inner loop

executes until the end in one iteration of the outer loop, because the whole inner loop is one

statement in the body of outer loop.
Combining loops and conditional statements, we can build powerful applications that do complex

jobs. For instance, we will create a program that determines whether a given number is a prime or

not.
import javax.swing.*;
class Prime{
public static void main(String[] args){
int x;
String userInput;
userInput=JOptionPane.showInputDialog("Enter a number");
x = Integer.parseInt(userInput);
//1, 2 and 3 are prime numbers
if(x == 1 || x == 2 || x == 3){
System.out.println(x + " is prime");
}
//All even numbers > 2 are not prime
else if(x % 2 == 0){
System.out.println(x + " is not prime");
}else{
//We have to check using division remainder
//we initially suppose that x is prime
boolean prime = true;
//No number has factor greater than it's half
for(int i = 3; i <= x / 2; i++){
if(x % i == 0){
//We have found a factor
//so x is not prime
prime = false;
break;
}
}
if(prime){
System.out.println(x + " is prime");
}
else{
System.out.println(x + " is not prime");
}
Java Lab Manual by Yasser Jaffal (2008)

44
}
}
}

To get more familiar, try to understand the following program that keeps reading numbers (integers)

from user until input is 0, then prints average, sum, maximum and minimum.
import java.io.*;
class Numbers{
public static void main(String[] args) throws IOException{
int min, max, x, sum = 0, count = 0;
boolean firstNumber = true;
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
while(true){
System.out.print("Enter a number: ");
x = Integer.parseInt(in.readLine());
if(x == 0){ break; }
if(firstNumber){
min = max = x;
firstNumber = false;
}
sum += x;
if(x > max){ max = x; }
if(x < min){ min = x; }
count++;
}

System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / count);
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
}
}
8.4 Variable Scope
By variable scope, we mean the region or block the variable is visible within, any access of

variable out of its scope will be reported as compilation error. Consider the following code.
Java Lab Manual by Yasser Jaffal (2008)

45
int x = -3;
if(x < 0){
int y = x * -1;
System.out.println("Absolute value of " + x + " is " + y);
}
In the previous code,
x
has scope inside and outside
if
block, while
y
is only visible inside
if

block, if you try to call
y
from outside
if
block, you will get error message
"Cannot resolve

symbol"
.
int x = -3;
if(x < 0){
int y = x * -1;
}
System.out.println("Absolute value of " + x + " is " + y); //Error
Variable scope extends from outer block to inner blocks regardless of the number of levels, but not

vise-versa.
//Visible: None
for(int i = 1; i <= 12; i++){
//Visible: i
for(int j = 1; j <= 12; j++){
//Visible: i, j, k
int k = i * j;
System.out.println(i + " * " + j + " = " + k);
}
//Visible: i
}
//Visible: None
Exercises
1.
Write a program that reads 10 numbers from the user then prints out how many positive

numbers and negative numbers user has entered (consider 0 a positive number).
2.
Modify calculation program in session 4 exercise 3 by adding the following question at the

end of the program:
Do you want to make another calculation?
1. Yes
2. No
Enter your option:
If user selects
yes
(by entering 1)
, program will ask him again to enter new two numbers and

select operation, if user selects
no
(by entering 2)
, program exits. Use appropriate loop to

accomplish this.
3.
Write a program that asks the user to enter certain number, after that asks him to enter

Java Lab Manual by Yasser Jaffal (2008)

46
another 20 numbers, after entering them all, it prints out the number of occurrences of the

first number. See the below example (text shown in boldface is supposed to be user input).
Enter number to search for:
2
Enter a number:
(20 times)
2 3 56 7 9 2 4 5 5 6 2 21 33 19 32 88 0 32 100 20
The number (2) occurred 3 times in your input.
4.
What is the output of the following program?
for(int i = 0; i < 5; i++){
for(int j = 0; j < i; j++){
System.out.print(" ");
}
System.out.print(i * j);
System.out.println("");
}
Lab Extras
We use
continue
keyword to skip some statements inside loop body and start new

iteration, consider the following program that prints out factors of 30.
for(int i = 1; i <= 30; i++){
if(30 % i != 0){ continue; }
System.out.println(i);
}
As you can see, when 30 is not divisible by
i
, we use
continue
to jump to the next iteration

without executing the next line that prints the output.
Java Lab Manual by Yasser Jaffal (2008)

47
Session 9
Arrays and Strings
Objectives

Understand the concept of arrays.

Defining and using arrays in different types.

Multidimensional arrays.

Strings as arrays.
9.1 What Are Arrays?
Arrays are special data types that let us store specified number of variables from the same

type using one variable name. Imagine the situation that you need to store 20 names of students as

strings and 20 integers as marks, then you need to define 40 variables, and this is clearly very hard

and not practical, in such case you need to use arrays. Arrays are
indexed
data types, that means

they are storing different elements discriminating between them using unique index for each one.

Figure 9.1 shows the structure of an array.
Figure 9.1: Array Structure
As Figure 9.1 shows, the size of an array is fixed, we will refer to array maximum size as
array

length
, it is also clear that indices of an array are zero-based, that is, they start from 0 to length – 1;

for example, the array shown in Figure 9.1 has a length of 10 (stores up to 10 elements), and the last

index is 9.
9.2 Using Arrays in Java
Declaring and using an array in Java is similar to declaration of any variable; you have to

specify data type and name, in addition to this, you have also to specify the length of the array

before using it. Array definition format is as follows:
DataType[] array
Name;
To initialize the array, use
new
keyword and specify the length.
arrayName = new DataType[length];
Here are some examples of array declaration:
int[] a = new int[6]; //Array of integers of length 6
String[] b = new String[10]; //Array of strings of length 10
Java Lab Manual by Yasser Jaffal (2008)

48
To access array members, use array name with desired index specified between square brackets [ ].
int[] x = new int[3]
;
x[0] = 5; //Store 5 in the first index
x[1] = 10; //Store 10 in the second index
x[2] = 15; //Store 15 in the third index
System.out.println(x[2] + x[1]); //Prints 25

If you try to access an index out of the range of array (greater or equals array length) JVM will

throw an
IndexOutOfRangeException
.
int[] x = new int[3]
; //Valid indices are 0, 1 and 2
x[3] = 7; //IndexOutOfRangeException
Another technique to declare an array is to directly provide its members between brackets
{
and
}
,

separated using commas '
,
'.
int[] x =
{10, 15, 20, 25, 100}; //Length = 5
System.out.println(x[3]); //Prints 25
String[] days = {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"};
//We are leaving in Monday
System.out.println("We are leaving in " + days[2]);
It is common to deal with arrays using for loop, we can use
length
property to determine the

length of the array. The following code stores multiples of 3 in an array then prints them from

greater to smaller.
int[] a = new int[20]
;
for(int i = 0; i < a.length; i++){
a[i] = i * 3;
}
for(int i = a.length – 1; i >= 0; i—){
System.out.print(a[i] + " ");
}
The following example stores names and numbers of n students and performs search.
import javax.swing.*;
class Students{
public static void main(String[] args){

int[] numbers;
String[] names;
String input =
JOptionPane.showInputDialog("Enter number of students");
Java Lab Manual by Yasser Jaffal (2008)

49
int size = Integer.parseInt(input);
numbers = new int[size];
names = new String[size];
for(int i = 0; i < numbers.length; i++){
names[i] =
JOptionPane.showInputDialog("Enter Student name");
input =
JOptionPane.showInputDialog("Enter Student number");
numbers[i] = Integer.parseInt(input);
}
/* Now we have all numbers and names, index will bind two
arrays together, that is, student in index 5 has his name

in names[5] and his number stored in numbers[5] */
//Search for student
int x;
do{
input =
JOptionPane.showInputDialog("Enter student number");
x = Integer.parseInt(input);
boolean found = false;

for(int i = 0; i < numbers.length; i++){
if(numbers[i] == x){
JOptionPane.showMessageDialog(null,
"Name: " + names[i]);
found = true;
break;
}
}
if(!found){
JoptionPane.showMessageDialog(null, "Not found");
}
//Ask if the user wants to perform another search.
input =
JoptionPane.showInputDialog("Search again? Y/N");
}while(!input.equalsIgnoreCase("N"));
}
}
Comments on the previous program:

Array index could be used to relate data from different arrays together.
Java Lab Manual by Yasser Jaffal (2008)

50

Output could be provided using
JOptionPane.showMessageDialog()
method

(Remember to provide
null
as first parameter (parent window) ).

String
class has method called
equalsIgnoreCase
that compares two strings together

regardless of their case. There is also another method called
equals
that makes case-
sensitive comparison between strings.
9.3 Multidimensional Arrays (Arrays of Arrays)
Up to this point, we were storing elements in linear manner, that is, we provide one index to

locate the element in one-dimensional structure. Java also provides
arrays of arrays
, this means we

create an array, each element in that array is an array itself. These arrays are also called

multidimensional arrays. Lets first consider the declaration of multidimensional arrays.
DataType[][] array
Name;
arrayName = new DataType[rows][columns]
The following example shows a definition of a 5 by 4 array of integers.
int[][] x = new int[5][4];
//i indicates row (row by row)
for(int i = 0; i < 5; i++){
//j indicates column (column by column)
for(int j = 0; j < 4; j++){
x[i][j] = i * j;
}
}
//Print array
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
System.out.print(x[i][j] + " ");
}
System.out.println("");
}
You can see from the previous example that we deal with each element in the array as array itself,

for example, we call
x[i].length
, this means that
x[i]
is an array of integers that may has its

own length, because it is not necessary that all rows have the same number of columns. The

following example shows that.
int[][] a = {
{0}, //a[0]
{0, 1}, //a[1]
{0, 1, 2}, //a[2]
{0, 1, 2, 3} //a[3]
};
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
Java Lab Manual by Yasser Jaffal (2008)

51
System.out.print(a[i][j] + " ");
}
System.out.println("");
}

The output of the above code is the following:
0
0 1
0 1 2
0 1 2 3
As you can see, we filled the array above with sub-arrays. Two dimensional arrays are common in

representing matrices, for example, we can write a program that adds two matrices (remember that

matrices must have same number of rows and same number of columns when it comes to addition).
import javax.swing.*;
class Matrices{
public static void main(String[] args){
String input;
int rows, columns;
input = JOptionPane.showInputDialog("Enter number of rows");
rows = Integer.parseInt(input);
input =
JOptioPane.showInputDialog("Enter number of columns");
columns = Integer.parseInt(input);
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
String m1 = "Enter first matrix elements\n";
String m2 = "Enter second matrix elements\n";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
input =
JOptionPane.showInputDialog(m1+"["+i+"]["+j+"]");
matrix1[i][j] = Integer.parseInt(input);
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
input =
JOptionPane.showInputDialog(m2+"["+i+"]["+j+"]");
matrix2[i][j] = Integer.parseInt(input);
}
Java Lab Manual by Yasser Jaffal (2008)

52
}
int[][] result = new int[rows][columns];
String output = "";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
result[i][j] = matrix1[i][j] + matrix2[i][j];
output += result[i][j] + "\t";
}
output += "\n";
}
JOptionPane.showMessageDialog(null, "Result is\n" + output);
}
}
9.4 String as Arrays
We can deal with strings as array of characters, this could be accomplished through two

methods in String class called
length()
and
charAt()
, the following example prints a string

putting each character in separate line.
String s = "Al-Quds";
for(int i = 0; i < s.length(); i++){
System.out.println(s.charAt(i));
}
Be ware of the difference between strings and arrays when accessing length;
length
in arrays is a

variable
so we call it without brackets, but in string,
length()
is a
method
so we call it with

brackets.
charAt()
method simply returns the character contained in the provided zero-based

index within the string, for example, calling
charAt(3)
in the previous example returns
'Q'
.
The following example counts how many spaces there are in certain string.
String a = "a string with four spaces";
int count = 0;
for(int i = 0; i < a.length(); i++){
if(a.charAt(i) == ' '){
count++;
}
}
System.out.print("There are " + count + " spaces in the string");
Exercises
1.
Write a program that reads 10 integers from the user and then prints them out in reverse

order.
2.
Write a program that reads names and marks of 10 students then prints the names of the

Java Lab Manual by Yasser Jaffal (2008)

53
students with the highest and lowest marks.
3.
Write a program that reads 16 integers from the user, stores them in 5 by 4 matrix, the last

row of the matrix should contain the sums of the columns (see figure 9.2) calculated by your

program. Then the whole matrix is printed.
User input
4
7
1
8
3
8
9
5
1
3
4
5
8
1
5
6
Sum
16
19
19
24
Figure 9.2 (Exercise 3)
Lab Extras
You may have noticed that when we declare the
main
method we specify an array of strings

String[] args
. This array stores command-line arguments and it could be used as input

method in addition to input methods we discussed earlier.
To see how it works, first we should know how to provide command line arguments, when we run a

class we use the following command.
java ClassName arg_1 arg_2 ... arg_n
The arguments we provide after class name are stored in
args
array, the number of arguments

determine the length of the array, notice that arguments are separated by spaces. The following

example shows how to read numbers from command line and print their sum.
class QuickSum{
public static void main(String[] args){
int sum = 0;

for(int i = 0; i < args.length; i++){
sum += Integer.parseInt(args[i]);
}

System.out.println("sum = " + sum);
}
}
Here is an example of the the execution of the above code.
java QuickSum 3 4 6 2
sum = 15
In NetBeans IDE, you can add command line arguments by opening project properties, selecting

"run" node from properties tree on the left, then entering arguments in "Arguments" field separated

by spaces.
Java Lab Manual by Yasser Jaffal (2008)

54
Session 10
Applications on Arrays (Databases)
Objectives:

Understand the concept of databases.

Implementing databases using arrays.

Performing search and update.
10.1 What Are Databases?
Databases are used to store large amount of data in one or more tables, in the large picture, these

tables have relations between them. What we are interested in right now is to understand the

concept of tables and how to implement them using Java arrays.
Consider for example that we have a table to store data about cars, this table is shown below (table

10.1).
Vendor
Model
Color
Mazda
1988
Red
Honda
1995
Silver
Fiat
2000
Blue
Honda
2002
Red
Nissan
2000
Black
Table 10.1: Cars database
What we are willing to do now is to see how can we represent this table in Java and modify or

retrieve data from it.
10.2 Implementing Databases using Arrays
In Java, you can use arrays to simulate tables of databases. This is a simple task based in array

index. For example, if we wish to represent the table 10.1 using arrays, we have to do the following:
1.
Specify appropriate data type for each column.
2.
Declare an array for each column of its selected data type.
3.
Insert data to arrays by putting each row entry in the same index in all arrays.
Lets say that we have selected
String
data type for both “Vendor” and “Color” columns and
int

for “Model”. We have to declare three arrays for them.
String[] vendor = new String[5];
String[] color = new String[5];
int[] model = new int[5];
One thing left, which is adding data to this table. Each row in the table will take a common index in

all arrays, for example, we represent the first row by setting the following.
Java Lab Manual by Yasser Jaffal (2008)

55
vendor[0] = "Mazda";
color[0] = "Red";
model[0] = 1988;
To represent the whole table, we can declare arrays as following.
String[] vendor = {"Mazda", "Honda" , "Fiat", "Honda", "Nissan"};
String[] color = {"Red" , "Silver" , "Blue", "Red" , "Black" };
int[] model = { 1988 , 1995 , 2000 , 2002 , 2000 };
It is possible now to search inside this table, for example, to find the cars manufactured in year

2000, we can do something like this.
for(int i = 0; i < model.length; i++){
if(model[i] == 2000){
System.out.println(vendor[i] + " - " + color[i]);
}
}
In a similar way, we can search by color or by vendor. Additionally, we can update table data by

updating arrays contents. For example, the following code sets all cars colors to red.
for(int i = 0; i < color.length; i++){
color[i] = "Red";
}
Exercises
1.
Write Java Applet that implements cars table. Your applet should have three buttons, a text

field and a text area (
TextArea
class is like
TextField
but have multiple lines). It

should look like figure 10.2 below. The following table shows how should this Applet

behave.
Button
Behavior
Vendor
Performs search using car's vendor and gives full details

about each matching car in the text area
Model
Similar to “By Vendor”, but performs search using model
Color
Similar to “By Vendor”, but performs search using color
Figure 10.2: Cars Applet
Java Lab Manual by Yasser Jaffal (2008)

56
Session 11
Applets and Graphics
Objectives:

Using
paint()
method to draw on Applets.

Calling
getGraphics()
to draw after Applet initialization.

Introducing different methods of
Graphics
object.
11.1
paint()
Method
As you have seen in session 5, Applets have two important methods,
init()
and
paint()
. We

have discussed
init()
method earlier, and it is now the time to have a look at
paint()
. The

code below shows this method.
class MyApp extends Applet{
public void paint(Graphics g){
}
}
The object g is used to draw on the Applet, for example, we can draw a line from the upper-left to

lower-right corners of the Applet. This example is shown in the code below. Result is shown in

figure 11.1 (in the next page).
import java.awt.*;
import java.applet.Applet;
public class LineApp extends Applet{
public void init(){
resize(200, 200);
}
public void paint(Graphics g){
g.drawLine(0, 0, getWidth(), getHeight());
}
}
The weakness of
paint()
method is that it is called automatically each time Applet repaints, so

you cannot control which graphics should be drawn at runtime. To solve this problem, we obtain

Graphics
object from any other method using
getGraphics()
method.
Java Lab Manual by Yasser Jaffal (2008)

57
Figure 11.1: Line Applet
The following example draws a circle at the upper-left corner of the Applet with the specified

radius. Notice how do we use
drawOval()
method.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Circles extends Applet implements ActionListener{
TextField value;
Button draw;
public void init(){
resize(400, 400);
draw = new Button("Draw");
value = new TextField();
draw.addActionListener(this);
add(value);
add(draw);
}
public void actionPerformed(ActionEvent e){

Graphics g = getGraphics();
int diameter = Integer.parseInt(value.getText()) * 2;

g.drawOval(0, 0, diameter, diameter);
}
}
Figure 11.2 on the next page shows an example of circles Applet.
Java Lab Manual by Yasser Jaffal (2008)

58
Figure 11.2: Circles Applet
Exercises
1.
Write a Java Applet that has 5 int fields, named
x1
,
x2
,
y1
,
y2
and
radius
. Add two

buttons to your Applet named “line” and “circle”. The behavior of these buttons should be

as shown in table 11.3 below.
Button
Functionality
Line
Draws line from (
x1
,
y1
) to (
x2
,
y2
)
Circle
Draws circle centered on (
x1
,
y1
) and has the radius

of the value entered in
radius
text field
Table 11.3
Figure 11.4 shows how should your Applet look like.
Figure 11.4: Exercise 1
Java Lab Manual by Yasser Jaffal (2008)

59
Session 12
Methods
Objectives

Introducing method structure.

Writing and calling methods.

Understanding return types and void methods.

Differentiating between passing by value and passing by reference.
12.1 What Are Methods
In programming, there are some common procedures we occasionally use, like reading input

from user, printing output on the screen and so on, those procedures are called
methods
. So far, we

have introduced a number of known methods like
println
and
readLine
, these methods are

previously written by developers of Java, so we can directly call and use them, and it is clear this

makes our work easier. To write a method, use the following definition format.
static
ReturnType methodName
(
param_1
,
param_2
, ...,
param_n
){
//Method body
return
returnValue
;
}
Using
static
keyword is not part of the format and there are more options for definition, but right

now, and as we will be calling our methods from the
main
method, we will use
static
in method

definition.
The contents of method definition are the following:

static
: because we will be calling our methods from the
main
method which is static, we

shall define our methods as static.

Return type: data type of the value this method will return, for example,

Integer.parseInt()
method returns integer data type, and
println
method does

not return any thing, so we call it void method. To define a void method, use
void
keyword

instead of return type in definition.

Method name: the name we will use to call our method, this name must be a valid variable

name (we discussed naming rules earlier). The naming convention for method name is like

variable name; first word starts with lower case letter, and rest of words start with upper

case letters.

List of parameters: method parameters provide an interface for providing input to method,

those parameters are variables specified by data type and name, separated by commas.

Method could take zero to infinity parameters, for example,
println
method takes one

parameter as string and prints that string on the console.

Method body: statements of the method, these statements are executed when method is

called.

return
: when a method has return type (not void), we have to terminate it using
return

keyword followed by the variable, value or expression that represents the value method

should return.
Java Lab Manual by Yasser Jaffal (2008)

60
12.2 Writing and Calling Methods
The following example shows how to add two numbers using method calling.
Technique 1: method takes parameters and prints the sum:
class Addition{
public static void main(String[] args){
int x = 5;
int y = 7;
sum(x, y);
}
static void sum(int a, int b){
int c = a + b;
System.out.println(c);
}
}
From the previous code you can notice the following:

No method is defined in the body of another one, so we define additional methods out of the

block of
main
method, but is still in the block of the class.

Method calling is simple and straight forward, all we have to do is to specify method name

and pass the parameters.

The method we have written is void, so it does not contain
return
statement.

When method is called, the value of
x
is copied into matching method parameter which is
a
,

similarly, the value of
y
is copied into
b
, so when
c
is calculated, it contains the sum of
x

and
y
.
Technique 2: method returns integer that contains the sum of two numbers.
class Addition{
public static void main(String[] args){
int x = 5;
int y = 7;
int z = sum(x, y);
System.out.println(z);
}
static int sum(int a, int b){
int c = a + b;
return c;
}
}
This time we specified integer as return type of the method, so we call it and assign the return value

to a new variable
z
, similar to parameter copying, the value of
c
returned from the method is copied

in
z
.
The advantage of returning the value is that gives programmer more options to do with the result

Java Lab Manual by Yasser Jaffal (2008)

61
instead of just printing it out, consider the situation in which we need to use our method to calculate

the sum of four values instead of two, it can be reached using second technique through calling the

method more than one time.
int z = sum(sum(2, 3), sum(1, 6));//z = 12
In the above example,
sum
is called 3 times, first time with 2 and 3 so it returns 5, second time with

1 and 6 so it returns 7, and the third time with the result of two previous calls 5 and 7 so it returns

12 which is the final result that is stored in
z
.
Lets have a look at more complex methods, and more useful ones. In the next example, we will try

to simplify the process of reading input by putting all of its steps in a single method with single call.
import java.io.*;
class ReadingSimplifier{
public static void main(String[] args){
String name = readString("Enter your name:");
int age = readInt("Enter your age:");
System.out.println("Welcome " + name);
System.out.println("Your birth year is " + (2007 – age));
}
static String readString(String message){
System.out.print(message);
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
try{
String input = in.readLine();
return input;
}catch(Exception e){}

return "";
}
static int readInt(String message){
String input = readString(message);
return Integer.parseInt(input);
}
}
You can see how we simplified reading from user by putting all necessary statements in a method

called
readString
that takes a string as parameter, this string is the message that will be

displayed for the user as input prompt,
readString
also returns a string that represents the value

entered by user. We use
try
and
catch
instead of throwing the exception, this eases code writing

by handling the exception so we no more need to declare our methods to throw it.
The second method we used is called
readNumber
, it takes a string to display for the user, passes

it to
readString
and get the value returned from it, then converts the returned value to integer

and returns it.
Java Lab Manual by Yasser Jaffal (2008)

62
12.3 Passing by Value and Passing by Reference
When methods are called, there are two different ways to pass parameters to method body,

the common way is
pass by value
, in which values are copied from the parameters to the local

values of the method, consider the following code.
//main
{
int x = 0;
add(x);
System.out.println(x);
}
static void add(int i){
i++;
}
If you compile and run the code above, the output you will see is 0, because the value of
x
was

copied into
i
, then the value of
i
was incremented, but
x
itself had never affected, because we did

not pass
x
, rather we passed its value.
On the other hand, all objects in Java are passed by reference, that is, the object itself is passed to

the method. A common example of objects passed by reference is passing an array object. Consider

the following code.
//main
{
int[] a = {0, 1};
add(a);
System.out.println(a[0]);
}
static void add(int[] x){
x[0] += x[1];
}
If you compile and run the above code, the output is 1. Because arrays are passes by reference, any

change we make on the array
x
inside add method is reflected on array
a
, because a and
x
are two

references to the same object.
12.4 Recursion
We can write a method that calls itself, these methods are called
recursive methods
, a

recursive method calls itself with different parameters to do certain job. For example, consider the

following method that calculates the factorial of a given integer
n
.
static int factorial(int n){
//Base case
if(n == 0 || n == 1){
return 1;
}
Java Lab Manual by Yasser Jaffal (2008)

63
//Recursive call
return n * factorial(n – 1);
}
As you can see, we build recursive methods using a
base case
and a
recursive call
, the base case is

the condition at which we stop the recursion. In the above code, for example, the base case is when

n
is equal to 0 or 1, both numbers have the factorial 1. The recursive call is executed if the base

case is not reached yet (i.e. there are more recursive calls until job is done), in case of factorial, we

build our recursive call using the mathematical fact which states that
n! = n (n – 1)!
, so we

return
n
multiplied by the factorial of
n – 1
. For example, if we tried to get the factorial of 4, the

execution of the method will flow like this:
1.
(n = 4) Is 4 = 0 or 4 = 1? No, so return 4 * (4 – 1)! (recursive call)
2.
(n = 3) Is 3 = 0 or 3 = 1? No, so return 3 * (3 – 1)! (recursive call)
3.
(n = 2) Is 2 = 0 or 2 = 1? No, so return 2 * (2 – 1)! (recursive call)
4.
(n = 1) Is 1 = 0 or 1 = 1? Yes, so return 1 (base case)
5.
1 is returned to the previous call and multiplied by 2
6.
The result of multiplication (2) is returned to the previous call and multiplied by 3
7.
The result of multiplication (6) is returned to the previous call and multiplied by 4
8.
The result of multiplication (24) is returned by the method as final result.
Exercises
1.
Write a method named
maxPosition
that takes an array of integers as array and returns

the index of the maximum element in the array.
2.
Write a method named
countChar
that takes two parameters: a string and a character,

then returns an integer representing number of occurrences of the character in the string.
3.
Write a method named
average
that takes array of doubles as parameter then returns the

average of the values inside the array. Sum calculation process should also be included in

method called
sum
that takes the array as parameter and returns the sum of its elements.
4.
Write a void method called
reverse
that takes a string as parameter and prints it in reverse

order and inverted letter case, for example if the input is
"Java"
, the output should be

"AVAj"
.
Hint: use integer values of characters to determine upper and lower cases.
5.
You will be given a lab on recursion on separate sheet and you have to solve it.
Java Lab Manual by Yasser Jaffal (2008)

64
Session 13
Object-Oriented Programming: Classes and Members
Objectives

Understanding the concept of Object-Oriented programming.

Introducing classes and objects and differences between them.

Understanding class members and their properties.

Understanding polymorphism and method / constructor overloading.
13.1 What is Object-Oriented Programming?
Object-Oriented programming is based on representing real life objects using software, this

representation includes both attributes and behavior, for example, if we want to represent a car in

Java, we have to specify its attributes and behavior as the following:
Attributes:

Engine No.

Chassis No.

Color.

Manufacturer.

Model name.

Manufacturing year.

Transmission (Automatic, Normal)

Number of wheels.
Behavior:

Move forward.

Move backwards.

Steer right.

Steer left.

Shift up.

Shift down.

Start engine.

Stop moving.

Stop engine.
We define this set of attributes and behavior in a class called Car, after creating this class, we can

define several
objects
of this class, that is, the class defines common properties among all cars, and

each object represents different car, so we may have, for example, objects like these:
1.
Car A: Color: red, Manufacturer: Nissan, Man. year: 1998, Transmission: Normal.
2.
Car B: Color: black, Number of wheels: 6.
3.
A.Start engine, A.Move forward and so on.
By the same way, we can represent any real-life object or any other object at any field, like circles

and triangles in representation of geometrical shapes.
13.2 Writing Classes in Java
So far, you have been writing a lot of classes, but these were far from the idea of

representing real-life objects, their rule was only to include the
main
method that we use to run the

program. We will start now to write classes that represent real-life objects, these classes does not

necessarily have main method and hence are not executable. For simplicity, we will leave the car

example to something more simple; a class that represents circle shape.
class Circle{
//Radius is enough to determine all circle attributes
public double radius;
Java Lab Manual by Yasser Jaffal (2008)

65
//Constructor
public Circle(double r){
radius = r;
}
//Methods
public double getRadius(){
return radius;
}
public double getArea(){
return (radius * radius) * Math.PI;
}
public double getCircumference(){
return 2 * Math.PI * radius;
}
public double getDiameter(){
return radius * 2;
}
}
The above class contained members declared using public keyword, this keyword means that the

member is accessible from outside the class, that is, when we declare an object from the class

Circle
, we can access all public members, even if we declare the object outside
Circle
class.
You can also notice a method that holds the same name of the class and does not has a return value,

actually, we call it
constructor
, constructors are used to determine the initial values necessary to

build objects and are used after
new
keyword in declaration, for example, when declaring a

Circle
object, we need to specify the radius of that circle, because all circle measurements are

based on the radius, so we write a constructor that takes radius as double. If we don't write a

constructor for our class, Java creates a
default constructor
that takes no parameters, but once we

write a constructor, the default constructor is no more available.
To declare a
Circle
object, we use something similar to variable declaration.
Circle c1 = new Circle(10);
Circle c2 = new Circle(12);
System.out.println("c1 Area is " + c1.getArea());
System.out.println("c2 Diameter is " + c2.getDiameter());
As shown above, declaring objects is straight forward, all you have to do is to specify class name

from which you create the object followed by object name, then you initialize the object using
new

keyword followed by a constructor with necessary parameters.
When we call a member from the object, we use dot
'.'
to access the members then specify

member name. As we declared radius to be public, we can access it just like any other members to

change the radius after declaration.
Circle c1 = new Circle(10);
Java Lab Manual by Yasser Jaffal (2008)

66
System.out.println("c1 Area is " + c1.getArea());
c1.radius = 15;
System.out.println("c1 Area is now " + c1.getArea());
13.3 Different Properties of Class Members
By properties of members, we mean set of access rules that controls how these members are

accessed and called from the class or an object of that class, we have introduced one of these

properties in
Circle
class which is
public
. Here is a list of access rules and their use:

public
: states that the member is accessible from outside the class (from another class).

private
: in the contrary of
public
,
private
states that the member is accessible only

from within the same class (a method or constructor inside the class).

static
: by
static
, we specify that a certain member can be called without declaring an

object (by calling class name followed by dot then member name). This is clear when

declaring
main
method, because when we run our class we do not declare an object from it.

It is important to know that static members cannot by called from non-static members and

vice versa, thats why we were declaring methods using
static
keyword, because
main
is

static, we have to declare any method we wish to call from
main
as static also. On the

variable level, the static variable is shared among all objects of the class.
For now, these properties are enough for us. The following example clearly explains the difference

between public and private members:
class A{
private int value = 10;
public int getValue(){ return value; }
public void setValue(int newValue){ value = newValue; }
}
class B{
public static void main(String[] args){
A a = new A();
System.out.println(a.value); //Error, value is private
}
}
Trying to access private member from outside the class reports compile-time error.
It is a common practice in Object-Oriented that we declare members that store values as private and

create
set
and
get
methods to access them, set methods are called
mutators
, and get methods are

called
accessors
.
In the above example, we can use accessors and mutators methods o access the value stored in class

A
as the following:
class B{
public static void main(String[] args){
A a = new A();
a.setValue(33); //Changes the value by mutator method
System.out.println(a.getValue()); //prints 33
Java Lab Manual by Yasser Jaffal (2008)

67
}
}
The following example shows the difference between static and non-static variables:
class StaticTest{
private static int a;
private int b;
public StaticTest(){
a = 0; b = 0;
}
//Accessors
public static int getA(){ return a; }
public int getB(){ return b; }
//Mutators
public static void setA(int newA){ a = newA; }
public void setB(int newB){ b = newB; }
}
class Main{
public static void main(String[] args){
StaticTest s1 = new StaticTest();
StaticTest s2 = new StaticTest();
System.out.println("s1 values:");
System.out.println("a =" + s1.getA() + ", b =" + s2.getB());
System.out.println("s2 values:");
System.out.println("a =" + s2.getA() + ", b =" + s2.getB());
s1.setA(5);
s1.setB(3);
System.out.println("\ns1 values:");
System.out.println("a =" + s1.getA() + ", b =" + s2.getB());
System.out.println("s2 values:");
System.out.println("a =" + s2.getA() + ", b =" + s2.getB());

}
}
Compiling and running the above code shows the following output:
s1 values:
a =0, b =0
s2 values:
a =0, b =0
Java Lab Manual by Yasser Jaffal (2008)

68
s1 values:
a =5, b =3
s2 values:
a =5, b =0
So what can be concluded from the output? The value of
b
is different for each object, changing

the value of
b
in object
s1
did not affect the value of
b
in
s2
, which is not the situation with
a
,

because changing the value of
a
in
s1
had its effect in
a
when called from
s2
, thats because static

members are shred among all objects as stated, variable a and methods related to it could be called

from the class name directly as shown below:
StaticTest.setA(13);
System.out.println(s1.getA() + " " + s2.getA());
In the above code,
println
method will print 13 two times. Remember to declare static methods

when dealing with static variables, back to
StaticTest
class definition, for example, you can

notice that
getA
and
setA
methods are declared static.
13.4 Methods and Constructors Overloading
Overloading means to have more than one constructor or more than one method having the same

name, because there are more than one way to discriminate between methods, including name and

number and type of parameters. To see how parameters can help in overloading, consider the

following constructors.
class Rectangle{
private double height, width;

public Rectangle(double h, double w){
height = h;
width = w;
}
public Rectangle(double d){
height = width = d;

}
public Rectangle(){
height = width = 1;
}
}
As the above example illustrates, we have three constructors having the same name, when we call a

constructor after
new
keyword, depending on parameters we specify a matching constructor is

selected.
Rectangle a = new Rectangle();//Third constructor
Rectangle b = new Rectangle(5);//Second constructor
Java Lab Manual by Yasser Jaffal (2008)

69
Rectangle c = new Rectangle(3, 4);//First constructor
It is important to realize that discriminating between constructors and methods holding the same

name are:
1.
Number of parameters.
2.
Order of parameters.
3.
Types of parameters.
So it is important to know that parameter name has nothing to do with overloading, the following

example shows this.
//This code generates error message.
class A{
private int value;
public void setValue(int t){
value = t;
}
public void setValue(int s){
value = s;
}
}
To better understand classes and objects, lets analyze a well-known statement we've been using

repeatedly:
System.out.println("Hello World");
System
is a name of a class, inside
System
class, there is a public and static member (object) of

class
PrintWriter
, the name of this object is
out
. Inside
PrintWriter
class, there is a

public, non-static method called
println
that has several overloads.
Exercises
1.
Write a class that represents triangle named
Triangle
, the class must have the following

members:

private double height;//Height

private double base;//Base length

public Triangle(double h, double b);//Constructor

public void setHeight(double x);//Sets height

public double getHeight();//Gets height

public void setBase(double x);//Sets base length

public double getBase();//Gets base length

public double getArea();//Returns the area of the triangle
2.
Write a class
Employee
that represents an employee of some organization, the class should

contain the following members:

private int id;//Employee id

private String name;//Employee name

private int type;//1 = employee, 2 = manager
Java Lab Manual by Yasser Jaffal (2008)

70

private double baseSalary;//Base salary

public Employee(int _id, String _name);//Constructor

public void setID(int x);//id mutator

public void setName(int x);//name mutator

public int getID();//id accessor

public String getName();//name accessor

public double getSalary();
//if manager, add 10% to base salary

public void setBaseSalary(double bs);//sets base salary.
Lab Extras
When we wish to specify a member from the class, we can use
this
keyword,
this
refers

to the current object of the class. For example, to discriminate between local and global variables in

a class that have the same name, we use
this
to specify which one in in the scope of whole class.
class Square{
private int sideLength;
public Square(int sideLength){
this.sideLength = sideLength;
}
public void setSideLength(int sideLength){
//global local
this.sideLength = sideLength;
}
}
As you can see, we have two variables called
sideLength
, one is global for the whole class and

it is where we store the value, and other is local for the constructor (or method), when we call

this.
, we are returning back to the scope of the class, so if we are to specify any member after

this
, it has to be a global member.
Another use of
this
keyword is to call a constructor from within another constructor,
this
itself

represents the call, so what you have to do is to pass parameters to
this
just like the way you pass

them to any constructor. This technique is common when writing default constructor that does not

require user to specify parameters.
class Vector{
private double length;
private double angle;
public Vector(double length, double angle){
this.length = length;
this.angle = angle;
}
public Vector(){
/* Calling the previous constructor,
Java Lab Manual by Yasser Jaffal (2008)

71
passing 1 as length and 0 as angle */
this(1, 0);
}
}
If you need to specify additional statements in the constructor from which you are calling another

constructor, these statements should be specified after
this
call, in other words, when using
this

to call another constructor, it should be in the first statement.
Java Lab Manual by Yasser Jaffal (2008)

72
Session 14
Exceptions and Error Handling
Objectives:

Understanding exception-throwing methods.

Using
try-catch
to handle exceptions.

Understanding and writing custom exceptions.
14.1 Exception-Throwing Methods
Runtime errors appear in Java as exceptions, exception is a special type of classes that could

be
thrown
to indicate a runtime error and provide additional data about that error. If a method is

declared to throw an exception, any other method calls it should deal with this exception by

throwing it (if it appears) or handle it. Recalling reading from user using
BufferedReader
class,

we used to declare main method from which we call
readLine()
using
throws

IOException
, this because
readLine()
is declared to throw that exception.
import java.io.*;
class ReadFromUser{
public static void main(String[] args) throws IOException{
.
.
.
}
}
If we wish to write a method that simplifies reading from user, you may want to declare it to throw

IOException
.
import java.io.*;
class ReadFromUser{
public static void main(String[] args) throws IOException{
String in = read("Enter your name: ");
}
public static String read(String message) throws IOException{
System.out.print(message);
BufferedReader in = new BufferedReader(
new

InputStreamReader(System.in));
String input = in.readLine();
return input;
}
}
In the previous code, if an exception occurs in
readLine()
method, this exception is thrown as it

Java Lab Manual by Yasser Jaffal (2008)

73
is to
read
method, which originally called it, because this last one is also declared to throw that

exception, it also throws it as it is to
main
method, which originally called it, finally, the exception

is throws to JVM which prints it out on the screen so the user can know there was error.
14.2
try-catch
Exception Handling
Another technique for handling runtime errors is to use
try-catch
block to handle

different types of exceptions and take appropriate action instead of throwing them to the user. The

format of
try-catch
block is the following.
try{
//Statement(s) that may throw exceptions
}catch(Exception e){
//Statement(s) to handle exception.
}
For example, we can place
readLine()
method which throws
IOException
in a
try-catch

block as the following.
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String input;
try{
input = in.readLine();
}catch(IOException e){
System.out.println("Error occurred");
}
When we are expecting more than one exception, we can use several catch blocks, each one for

different type of exceptions. For example, when reading a string using
BufferedReader
and

converting it to integer, you can expect two different exceptions:
IOException
and

NumberFormatException
which occurs when the provided string cannot be converted to

integer.
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String input;
try{
input = in.readLine();
int x = Integer.parseInt(input);
}catch(IOException e){
System.out.println("Error reading input");
}catch(NumberFormatException err){
System.out.println("This is not a valid number");
}
14.3 Writing Custom Exceptions
In some cases while developing our own applications, we need to specify custom types of

Java Lab Manual by Yasser Jaffal (2008)

74
exceptions to handle custom errors that may occur during program execution. A custom exception

is a class that
inherits

Exception
class or any of its subclasses, since inheritance is beyond the

scope of this course, we will define it as using
extends Exception
in class declaration.
class MyCustomException extends Exception{

private String message;
public MyCustomException(String message){
this.message = message;
}
public String toString(){
return message;
}
}
To use your custom exception, declare an object of it and throw that object using
throw
keyword.

It is optional to declare the method containing
throw
statement with
throws
keyword.
In the following example, the program reads student id, this id should be of length 7 and consists

only of digits, otherwise it throws an exception.
class InvalidIDException extends Exception{

private String message;
public InvalidIDException(String message){
this.message = message;
}
public String toString(){
return message;
}
}
Import javax.swing.*;
class StudentsData{
public static void main(String[] args){
String id, name;
name = JOptionPane.showInputDialog("Enter student name");
id = JOptionPane.showInputDialog("Enter student ID");

try{
verfyID(id);
}
catch(InvalidIDException e){
JoptionPane.showMessageDialog(null, e.toString());
}
Java Lab Manual by Yasser Jaffal (2008)

75
}
public static void verifyID(String id)
throws InvalidIDException{
if(id.length() != 7){
throw new InvalidIDException("Check ID length");
}
try{
Long.parseLong(id);
}
catch(Exception err){
throw
new InvalidIDException("ID can contain only digits");
}
}
}
Exercises
1.
Write a program that count how many prime numbers between minimum and maximum

values provided by user. If minimum value is greater than or equal to maximum value, the

program should throw a
InvalidRange
exception and handle it to display a message to

the user on the following format:Invalid range:
minimum
is greater than or equal to

maximum.
For example, if the user provided 10 as maximum and 20 as minimum, the

message should be: Invalid range: 20 is greater than or equal to 10.
Lab Extras
In order to access the exception from the class it uses, there is an important aspect one should be

aware of which is
packaging
, packaging means putting two or more classes in the same
package
by

stating package name before declaring class (and also exceptions). When two classes are in the

same package, it is possible to access any one of them from the other, for example, if we have a

class named
Student
that represents a student, another class named
Main
to run a program that

manages student information, and a third class called
StudentDataException
that represent

any errors in student information, we can access
Student
and
StudentDataException

classes from
Main
class and define several objects of it if we use the following statement before

each class declaration:
package studentinfo;
In NetBeans IDE, there is no need to manually write the above statement, by adding new class to

any package of your project, that class is automatically declared as a part of that package. Figure

14.1 shows packages and classes in NetBeans IDE project explorer.
Java Lab Manual by Yasser Jaffal (2008)

76
Figure 14.1: Packages (shown as golden cubes)
and classes in NetBeans IDE project explorer
To access a class from its package we simply provide package name followed by dot '
.
' then

desired class name. For example, we can access Main class show in Figure 14.1 by calling it in the

following statement:
linkedlist.Main
Java Lab Manual by Yasser Jaffal (2008)

77