Sunteți pe pagina 1din 94

WORKBOOK ACTIVITY

(LABORATORY EXERCISES)

DFT4024 OBJECT ORIENTED


PROGRAMMING

1
Table of Contents

TOPICS PAGES
Introduction to Object Oriented
LAB 1 Programming
Introduction to Object Oriented
LAB 2 Programming

LAB 3 Introduction to Java programming

LAB 4 Fundamental of Java programming

LAB 5 Branching statements

LAB 6 Arrays

LAB 7 Classes, Inheritance and Polymorphism

LAB 8 Classes, Inheritance and Polymorphism

LAB 9 Classes, Inheritance and Polymorphism

LAB 10 Classes, Inheritance and Polymorphism

LAB 11 Classes, Inheritance and Polymorphism

LAB 12 Multithreading and Exception Handling

LAB 13 Multithreading and Exception Handling

2
LAB 1: Introduction to Object oriented
Programming

Learning Outcomes
This Lab sheet encompasses 5 activities. (Activity 1A, 1B, 1C, 1D and 1E)

By the end of this lab, students should be able to :


Illustrate the basic terminologies of OOP: Classes, Object, Encapsulation, Data Abstraction,
Inheritance and Polymorphism.
Distinguish between abstraction and encapsulation

Hardware / software : Mah-jong paper (if needed)

Activity 1A (CLO1)
Activity Outcome: Illustrate the basic terminologies of OOP: Classes

Procedure:

Step 1: Based on below Car class figure, identify class, object and it relationship with attributes and
method.
Step 2: Fill in the identification output in designated blank space.

3
Activity 1B (CLO1)

Activity Outcome: Illustrate the basic terminologies of OOP: Object

Procedure:
Step 1: Based on below MyCar object from class Car, identify object and it relationship with attributes
and method.
Step 2: Fill in the identification output in designated blank space.

Activity 1C (CLO1)

Activity Outcome: Illustrate the basic terminologies of OOP: Classes and Object

Procedure:

Step 1: By using concept of class and object in OOP, illustrate Class Phone and Object MyPhone
by including it relationship with attributes and method.
Step 2: Put both Class Phone and Object MyPhone into figure diagram as of Activity 1A and 1B.
Step 3: Share and present the outcome of Class Phone and Object MyPhone

4
Activity 1D (CLO1)

Activity Outcome: Illustrate the basic terminologies of OOP: Encapsulation Inheritance and
Polymorphism.

Procedure:

Step 1: Identify 3 OOP terminologies based on figure below


Step 4: Fill in the output in the blank space provided below.

a.

5
b.

c.

6
Activity 1E (CLO1)

Activity Outcome: Distinguish between abstraction and encapsulation.

Group Discussion Procedure:


(use mah-jong paper)

Step 1: List down the different between Abstraction and Encapsulation in Object Oriented
Programming.
Step 2: , Every group will compile all the differences and write down in flip chart (paper / mah-jong paper).
Step 3: A representative (selected by the lecturer) from each group will present their sharing

Activity 1F (CLO1)

Activity Outcome: Illustrate the basic terminologies of OOP: Encapsulation, Data Abstraction, Inheritance
and Polymorphism.

Procedure:

Step 1: Define the 4 basic concept of OOP.


Step 2: List down advantages of each concept
Step 3: Give real example of each of the concept.
Step 4: Fill in the output in the table provided below.

OOP Concept Definition Benefits Real World Example

Encapsulation

Data
Abstraction

Inheritance

Polymorphism

7
Reflection:

I can list the basic terminologies of OOP. Explain.

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

I can explain the basic terminologies of OOP. Explain.

_________________________________________________________________________

_________________________________________________________________________

________________________________________________________________________

I can differentiate between abstraction and encapsulation in OOP. Explain.

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

8
LAB 2: Introduction to Object oriented
Programming
Learning Outcomes
This Lab sheet encompasses 5 activities. (Activity 2A, 2B, 2C, 2D and 2E).

By the end of this laboratory activity session, you should be able to:
Understand the fundamental of Unified Modelling Language(UML).
Describe general UML elements.
Design classes using UML Class Diagram.
Identify components of a class:
a. structuring classes
b. class declaration
c. variable declaration and assignments
d. comments
e. methods

Hardware/ software : mah-jong paper (if needed)

Activity 2A (CLO1)

Activity outcome : Review the fundamental of Unified Modelling Language(UML).

9
Activity 2B (CLO2)

Activity outcome : Design Class Diagram

Assume that youre a Polytechnics soccer team leader. Your team are going to play match for Majlis
Sukan Politeknik. You are instructed to collect the details such as name, ic_number and phone number of
your team members. In this kind of situation, the class, objects, attributes and operations are identified.
Illustrate the UML class diagram for this situation.

Procedures :
Step 1: Analysis and identify from the following information.

i. The name of the class can be considered as SoccerTeam.


ii. Each student of the class namely, student1 (Faiz), student2 (Aiman), student3 (Qayyum) and
so on, can be considered as the objects or instances of the class SoccerTeam.
iii. The name, ic_number and phone number are the data of the object. Each student will have
his own data. These details are collected from the students.
iv. Getting the details of each student is the function performed on the data. Hence accept() is
considered as the function.

Step 2: Summaries and categories into a representation of the class.

Class Objects Attributes Operation

10
Step 3: Illustrate using Class Diagram

Answer :

Step 4: Type a program based on the above Class Diagram in java programming languages.

Answer :

11
Activity 2C (CLO1)

Activity outcome : Identify components of a class.

Based on the java program below, identify the component X, Y and Z.

public class Book X


{

String book_name;

String author_name; Y

void displayData() Z
{

System.out.println("Book Name:"+book_name);

System.out.println("Author Name: "+author_name);

12
Reflection:

I can understand the basic concept of UML class diagram. Explain.

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

I can identify the components of UML class diagram. Draw and explain.

_________________________________________________________________________

_________________________________________________________________________

________________________________________________________________________

I can identify the components of a class. Explain.

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

13
LAB 3: Introduction to Java Programming

Learning Outcomes:

This lab sheet encompasses 10 activities (Activity 3A, 3B, 3C, 3D, 3E, 3F, 3G, 3H, 3I
and 3J).

By the end of this laboratory session, you should be able to:

1. Identify the features of Java programming language.


2. Apply programming style and documentation in Java.
3. Write, compile and run the Java programs.
4. Troubleshoot the source code to identify the errors in Java.

Hardware/Software: Computer with JDK latest version.

Activity 3A (CLO1)
Activity Outcome: Students are able to identify and explain the features of Java programming language.

Procedure:
1. Divide class into 3 to 4 person in group. Appoint one student from each group as the leader.
2. Each group will discuss only one of the features of Java programming language in 10 minutes.
3. Every group will discuss the different features of Java programming.
4. After that, each group will present in class about 5 minutes for each group.
5. By the end of this session, every group will compile all of the features of Java programming and write
down in flip chart (mah-jong paper).

Activity 3B (CLO2)
Activity Outcome : Identify the anatomy of the Java Program.

Procedure:
1. Analyze the HelloWorldApp program
2. Complete the following table with the correct line number and code of Java program:

1. /* Activity 3B */

2. class HelloWorldApp {
3. public static void main(String[] args)
4. {
5. System.out.println("Hello World!");
6. }
7. }

14
No Components Line No Corresponding Code
/* The HelloWorldApp class implements an application that
1. Comments 1 simply prints "Hello World!" to standard output. */

2. Class name 2 HelloWorldApp


3. Access modifier 3 public
4. Argument 3 args
5. Static method 3 public static void main(String[] args)

Activity 3C (CLO2)
Activity Outcome: Identify programming style and documentation in Java.
Write java program with programming style and documentation.

Procedure:
Step 1: Open Notepad and type the following code:

/* Activity 3C */

class Act3C // define class name


{ // open curly brace the beginning of class block

// main program where the program start


public static void main(String[] args)
{ // open curly brace for main block
//statement to print string
System.out.println("Hello, my name is Ayuni.");
System.out.println("\tIm from Semporna, Sabah.");
} //close curly brace for main block
} //end of class with close curly brace for body of block class

Step 2: Save, compile and run the program. Save the program as Act3C.java. Write the output in
the area below.

Output:

15
Activity 3D (CLO2)
Activity Outcome: Identify programming style and documentation in Java.
Write java program with programming style and documentation.

Procedure:
Step 1: Open Notepad and type the following code:

/* Activity 3D */

class Act3D // define class name


{ // open curly brace the beginning of class block

// main program where the program start


public static void main(String[] args)
{ // open curly brace for main block
//statement to print string
System.out.print("Hello, friends!");
System.out.print("My name is Mikail.");
System.out.print("I love to learn Java language.");
}//close curly brace for main block
}//end of class with close curly brace for body of block class

Step 2: Save, compile and run the program. Save the program as Act3D.java. Write the output in
the area below.

Output:

Activity 3E (CLO2)
Activity Outcome: Identify programming style and documentation in Java.
Write java program with programming style and documentation.

Procedure:
Step 1: Open Notepad and type the following code:

16
/* Activity 3E */

class Act3E // define class name


{ // open curly brace the beginning of class block

// main program where the program start


public static void main(String[] args)
{ // open curly brace for main block
//statement to print string
System.out.println("Hello, friends!);
System.out.println("My name is Mikail.");
System.out.println("I love to learn Java language.");
}//close curly brace for main block
}//end of class with close curly brace for body of block class

Step 2: Save, compile and run the program. Save the program as Act3E.java.
Write the output in the area below and explain the difference between output in Act3D and Act3E.

Output:

Activity 3F (CLO2)
Activity Outcome: Identify programming style and documentation in Java program.
Write java program with programming style and do documentation.

Procedures :
Step 1 : Open Notepad and type the following code:

/* Activity 3F */
public class Act3F { public static void main(String[] args) {
int number1 = 11; int number2 = 22; int number3 = 33; int number4 = 44;
int number5 = 55; int sum;
sum = number1 + number2 + number3 + number4 + number5;
System.out.print("The sum is ");
System.out.println(sum); }}

Step 2 : Add the appropriate comments and comment style, proper indention and spacing and block
styles
Step 3 : Save, compile and run the program. Save the program as Act3F.java. Write the output in
the area below.

Output:

17
Activity 3G (CLO2)
Activity Outcome: Identify programming errors in Java program.
Identify the errors and modify the program to fix the error(s).

/* Activity 3G */

Class Act3G
{
public static void Main(String[] args)
[
System.out.println ("I Love Java Programming!);
System.out.println ("I know how to write Java Program!);
System.out.print (It is simple and easy.)
)
}

Activity 3H (CLO2)
Activity Outcome: Identify programming errors in Java program.
Identify the errors and modify the program to fix the error(s).

/* Activity 3H //

class Act3H
{
public static void Main(String[] args)
{
double price1=50.65;
double total = price1/0;
System.out.println (Total price is +total);

}
}

Write the correct program below:

Program:

18
Activity 3I (CLO2)
Activity Outcome: Identify programming errors in Java.
Identify syntax errors in Java, implements programming style and documentation.

Procedures :
Step 1 : Open Notepad and type the following code:

/* Activity 3I */

Class Act3I {
public Static void main(String[] args) {
Sytem.out.prntln("Hello World!");
}
}

Step 2 : Save the program as Act3I.java in the working directory, compile and run the program.
Step 3 : Observe the output.
Step 4: Identify the syntax error and correct the syntax errors.
Step 5 : Save your program, compile and run the program again.

Output:

Activity 3J (CLO2)
Activity Outcome: Identify programming errors in Java.
Identify logic errors in Java, implements programming style and documentation.

Procedures :

Step 1 : Open Notepad and type the following code:

/* Activity 3J */

class Act3J {
public static void main(String[] args) {
int mark = 59;
if (mark < 50) // programmer mistake but syntaxly correct
System.out.println(PASSED);
else
System.out.println(FAILED);
}
}

Step 2 : Save the program as Act3J.java in the working directory, compile and run the program.
Step 3 : Observe the output.
Step 4: Identify the logic error and correct the logic errors.
Step 5 : Save your program, compile and run the program again.

Output:

19
Reflection:

I can understand the features of Java programming, that is

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

I can list the escape sequences for character values that are used in Java programming,
that are

_________________________________________________________________________

_________________________________________________________________________

________________________________________________________________________

I can identify the types errors can be occur in Java program. Write an example for each
types of error.

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

20
LAB 4: Fundamental of Java Programming

Learning Outcomes:

This lab sheet encompasses 11 activities (Activitiy 4A, 4B, 4C, 4D, 4E, 4F, 4G, 4H, 4I,
4J and 4K)

By the end of this laboratory session, you should be able to:

5. Identify and use identifiers, variables and constants in Java programming.


6. Identify and implement the mathematical, relational and conditional operators in
Java programming.
7. Implement type casting to change the data type
8. Implement input stream (System.in) and output stream (System.out) in Java
programming.
9. Write Java program using variables, operators and Input/Output stream

Hardware/Software: Computer with JDK latest version.

Activity 4A (CLO2)
Activity Outcome: Identify identifies, variables and constants in Java programming
Program below illustrates the declaration and initialization of variables of byte, short, int and long data
type.

Procedure:
Step 1: Open Notepad and type the following code:

class Act4A
{
public static void main(String[] args){

// declare variable b as numberB, initialized value,100 into it.


byte numberB = 100;

// declare variable s as numberS, initialized 3 value to it


short numberS = 3;

// declare variable numberI as integer, initialized 65 value to it


int numberI = 65;

//declare variable numberL as long, initialized 123456789 value to it


long numberL = 123456789;

//declare variable grade as char, initialized A value to it


char grade = 'A';

//declare numberF as float, initialized 3500 to it


float numberF = 3500;

21
//declare numberD as double, initialized 525.9 to it
double numberD = 525.9;

//declare isPermanent as boolean, initialized true to it


boolean isPermanent = true;

//display value of variables


System.out.println(numberB+","+numberS+","+numberI+","+numberL);
System.out.println(numberF+","+numberD+","+grade+","+isPermanent);

}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4A.java. Write the output in
the area below.

Output:

Activity 4B (CLO2)
Activity Outcome: Identify identifies, variables and constants in Java programming.

Program below illustrates variable and constant declarations:

Procedure:
Step 1: Open Notepad and type the following code:

class Act4B
{
public static void main(String[] args)
{
//declare variables radius as int, initialized value 3 to radius.
int radius=3;

//declare constant pi as double, initialized value 3.14 to pi.


final double pi=3.14;

//declare circumference as double.


double circumference;
circumference=2*pi*3;

//display output circumference


System.out.println(circumference);
}//end main()
Procedure:
}//end class

Step 2: Save, compile and run the program. Save the program as Act4B.java. Write the output in
the area below.

22
Output:

Activity 4C (CLO2)
Activity Outcome : Implement numeric data types in Java Program.

The following program uses primitive data type of byte and short:

Procedures:
Step 1: Open Notepad and type the following code:

class Act4C
{
public static void main (String[] args)
{
byte value = 127; //declare & initial variable
System.out.println("Value = " + value);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4C.java. Observe the output.
Step 3: Change the value of variable values from 127 to 128.
Step 4: Compile and run the program. Observe the output.

Output:

Step 5: Change the value variable values to -129 and try to compile and run the program. What
happens?
Output:

Step 6: Change the data type to short. Compile and run the program. Is there a difference? Explain.

Explanation:

23
Activity 4D (CLO2)
Activity Outcome : Implement numeric data types in Java Program.
The following program uses primitive data type of float and double:

Procedures:
Step 1: Open Notepad and type the following code:

class Act4D
{
public static void main ( String[] args )
{
//declare constant
final float VALUE_TAX = 3.4E038F;
System.out.println("Value = " + value);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4D.java. Observe the output.
Output:

Step 3: Change the value of constant values from 3.4E038F to 3.4E039F.


Step 4: Compile and run the program. Observe the output.

Output:

Explanation:
_______________________________________________________________________________
_______________________________________________________________________________

Step 5: Change the data type of constant values to double. Compile and run the program. Is there a
difference? Explain.

Output:

Explanation:
_______________________________________________________________________________
_______________________________________________________________________________

Step 6: Change the value of constant values from 3.4E038F to 1.7e308D.


Step 7: Compile and run the program. Observe the output.

Output:

Explanation:
_______________________________________________________________________________
_______________________________________________________________________________

24
Activity 4E (CLO2)
Activity Outcome: Implements character and Boolean data types in Java programs.
The following program uses primitive data type of character and boolean :

Procedures:
Step 1: Open Notepad and type the following code:

//Activity 4E
public class Act4E {
public static void main(String[] args) {
//declare variable
char letter;
boolean bool;

//initial@assign value to variable dan display it


letter = 'A';
System.out.println(letter);

letter = 'B';
System.out.println(letter);
bool = true;
System.out.println(bool);

bool = false;
System.out.println(bool);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4E.java. Observe the output.

Output:

Activity 4F (CLO2)
Activity Outcome: Implements mathematical, relational & conditional operators in Java programs.
The following program shows the precedence of the operators, relational & conditional operators.

Procedures:
Step 1: Open Notepad and type the following code:

25
class Act4F{
public static void main (String[] args)
{
//implement precedence of the operators
System.out.println(6 * 2 / 3);
System.out.println(9 + 12 * (8-3));
System.out.println(9 + 12 * 8 - 3);
System.out.println(5 + 19 % 3 - 1);

//implement relational operators


int num1=12;
System.out.println(num1==12);
System.out.println(num1!=12);
if(num1>=0)
System.out.println(This is positif number);
else
System.out.println(This is negetive number);

//implement conditional operators


int num2=4, num3=6;
if((num2<3) && (num3<10))
System.out.println(num2 and num3 are in range.);
Step 2: Save, compile and run the program. Save the program as Act4F.java. Observe the output.
if((num>0)||(num3<4))
System.out.println(num2 and num3 are in range.);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4F.java. Observe the output.

Output:

Activity 4G (CLO2)
Activity Outcome: Implements typecasting in Java programs.
The following program shows the implicit and explicit type casting.

Procedures:
Step 1: Open Notepad and type the following code:

26
class Act4G {
public static void main (String[] args)
{
System.out.println("Variables created");
//variable declaration & initialization
char char1= 'x';
byte numB= 50;
short numS1 = 1996;
int numI = 32770;
long numL= 1234567654321L;
float numF1 = 3.142F;
float numF2 = 1.2e-5F;
double numD = 0.000000987;

//display the value of each variable


System.out.println("char1 = " + char1);
System.out.println("numB = " + numB);
System.out.println("numS1 = " + numS1);
System.out.println("numI = " + numI);
System.out.println("numL = " + numL);
System.out.println("numF1 = " +numF1);
System.out.println("numF2 = " + numF2);
System.out.println("numD = " + numD);
System.out.println(" ");

System.out.println(" Types converted" );


short numS2 = numB; // implicit type casting
short numS3 = (short) numI; //explicit type casting

//from integer change to floating point


float numF3 = (float) numI;

//from floating point turn to be integral type


int numI2 = (int) numF1;

//display the output


System.out.println(" short numS2 = " + numS2);
System.out.println(" short numS3 = " + (short)numI);
System.out.println(" float numF3 = " + numF3);
System.out.println(" int numI2 = " + numI2);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4G.java. Observe the output.

Output:

27
Activity 4H (CLO2)
Activity Outcome: Implements input stream (System.in) and output stream (System.out) in Java
programs.

The following program show how to accepts input data using input stream, convert string value to integer
and display data using output stream .

Procedures:
Step 1: Open Notepad and type the following code:

//import package io to use InputStreamReader & BufferedReader class


import java.io.*;

class Act4H
{
public static void main (String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);

//declare variable
String str;
int num;

System.out.println("Enter an integer:");
str = stdin.readLine(); //read input that is entered by user
num = Integer.parseInt(str); // convert str to int

//display an input that was entered by user


System.out.println("You have entered an integer value of "+num);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4H.java. Observe the output.

Output:

28
Activity 4I (CLO2)
Activity Outcome: Implements input stream (System.in) and output stream (System.out) in Java
programs.

The following program below show how to accept input from the command line.

Procedures:
Step 1: Open Notepad and type the following code:

//import package io to use InputStreamReader & BufferedReader class


import java.io.*;

class Act4I
{
public static void main (String[] args) throws IOException
{
BufferedReader inData = new BufferedReader(new
InputStreamReader(System.in));

//declare variable
String str;

System.out.println("Enter the data : ");


str = stdin.readLine();//read input that is entered by user

//display an output, str value


System.out.println("You have entered: " + str);
}//end main()
}//end class

Step 2: Save, compile and run the program. Save the program as Act4I.java. Observe the output.

Output:

Activity 4J (CLO2)
Activity Outcome: Implements input stream (System.in) and output stream (System.out) in Java
programs.

The following program below show how to accept input and use mathematical operator to calculate the
numbers that is entered by user.

Procedures:
Step 1: Open Notepad and type the following code:

29
//import package io to use InputStreamReader & BuffredReader class
import java.io.*;

class Act4J
{
public static void main (String[] args) throws IOException
{
BufferedReader inData = new BufferedReader(new
InputStreamReader(System.in));

//declare variable
String str;
String num1, num2, num3;
int number1, number2, number3;

System.out.println("Enter your name : ");


str = stdin.readLine();//read input that is entered by user

System.out.println("Enter first number : ");


num1 = stdin.readLine();//read input that is entered by user
//convert @parsing String(num1) to integer data type
number1=Integer.parseInt(num1);

System.out.println("Enter second number : ");


num2 = stdin.readLine();//read input that is entered by user
//convert @parsing String(num1) to integer data type
number2=Integer.parseInt(num2);

System.out.println("Enter third number : ");


num3 = stdin.readLine();//read input that is entered by user
//convert @parsing String(num1) to integer data type
number3=Integer.parseInt(num3);

//calculate number1, number2 & number3


int total = number1+number2*(number3/number1);

//display output
System.out.println("Details:");

System.out.println("Name entered: " + str);


System.out.println("Number entered: " + number1 +
"," + number2 + "," + number3);
System.out.println(The total is: + total);
}//end main()
}//end class

30
Step 2: Save, compile and run the program. Save the program as Act4J.java. Observe the output.
Output:

Activity 4K (CLO2)
Activity Outcome: Implements input stream (System.in) and output stream (System.out) in Java
programs.
The following program show how to accept input and use mathematical operator to calculate the numbers
entered by user. This program is used Scanner class from util package to accept input from user.

Procedures:
Step 1: Open Notepad and type the following code:

//import util package to use Scanner class


import java.util.*;

class Act4K {
public static void main(String[] args) {
System.out.println("Enter any THREE numbers : ");
//create object of Scanner to invoke method from Scanner class.
Scanner sc = new Scanner(System.in);
/*A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then
be converted into values of different types using the various next
methods.*/

int num1 = sc.nextInt();


int num2 = sc.nextInt();
int num3 = sc.nextInt();

//calculate num1, num2, num3


int sum = num1*num2-num3;

//display an output, sum


System.out.println("The sum is: "+sum);
}//end main()
}//end class
Step 2: Save, compile and run the program. Save the program as Act4K.java. Observe the output.

Output:

State the differences between InputStreamReader class and Scanner class:

31
Reflection:

I can understand the identifiers, variable and constant in java. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand the use of operator in Java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand input stream and output stream. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

32
LAB 5: Branching Statements

Learning Outcomes:
This lab sheet encompasses 8 activities (Activity 5A, 5B, 5C, 5D, 5E, 5F, 5G and 5H).

By the end of this laboratory session, you should be able to:


1. explain selection and looping statements.
2. write program using selection and looping statements.

Hardware / Software: Computer with JDK latest version.

Theory/ Terminologies:
Statement that is used to select or branches to one of the alternative blocks for
execution is called Branching Statements. It has the following categories:

1. If Statement
2. The If else Statement
3. Nested if Statement
4. Switch Statement

Looping statement is used to execute a set of instructions repeatedly, as long as the


specific condition is satisfied. The looping statements available in Java are:
1. For
2. While
3. Do..while

33
Activity 5A (CLO2)
Activity Outcome: Write a program to demonstrate if else statements.

Procedures:
Step 1: Open Notepad and type the following code:
class Act5A
{
public static void main(String[] args)
{
int testscore = 76;
char grade;
if (testscore>= 80)
grade = 'A';
else
if (testscore>= 70)
grade = 'B';
else
if (testscore>= 60)
grade = 'C';
else
if (testscore>= 50)
grade = 'D';
else
grade = 'F';
System.out.println ("Grade = " + grade);
}
}

Step 2: Save, compile and run the program. Save the program as Act5A.java. Observe the output.

Activity 5B (CLO2)
Activity Outcome: Write a program to demonstrate switch case statements.

Procedures:
Step 1: Open Notepad and type the following code:

class Act5B
{
public static void main (String args[])
{
int value = 2;
if (value != 0)
if (value > 0)
System.out.println ("The result = " + (1 / value));
else
System.out.println ("We need a positive number.");
}
}

34
Step 2: Save, compile and run the program. Save the program as Act5B.java. Observe the output.

Activity 5C (CLO2)
Activity Outcome: Write a program to demonstrate switch case statements.

Procedures:
Step 1: Open Notepad and type the following code:
import java.io.*;
class Act5C
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader (new
InputStreamReader (System.in));

int input, answer;


System.out.println("Enter the number:");
input = Integer.parseInt(stdin.readLine());

switch(input)
{
case 1:
answer = (10+input);
System.out.println("The answer is :" + answer);
break;

case 2:
answer = (10-input);
System.out.println("The answer is: " + answer);
break;

default:
System.out.println("Invalid input");
}
}
}

Step 2: Save, compile and run the program. Save the program as Act5C.java. Observe the output.

35
Activity 5D (CLO2)
Activity Outcome: Write a program to demonstrate if-else statements.

Students are required to write a program named PaymentMethod.java that has TWO (2) options which
is Online Banking or Credit Card. If user chooses Online Banking, display to the user The supported
bank is Bank Islam, Maybank and CIMB, and display VISA only if they choose payment by Credit Card

Procedures:

Step 1: Create new Java file, name as PaymentMethod.java


Step 2: Open file PaymentMethod.java and rewrite the following programming code.

Step 3: Build successful the program and run to see the output.
Step 4: Write the output in the box below.

36
Activity 5E (CLO2)
Activity Outcome: Write a program to demonstrate Compound-Relational Test

Students are required to write a program named MembershipRequirement.java where user need to
be at least 21 years old and has yearly income more MYR 21,600 in order to be eligible. The program will
prompt the user to enter their age and salary. If both are satisfied, the system will display Congratulation,
you are eligible to a membership!. If one of them are not, the system will display Sorry, you are not
eligible to any membership, please try again.

Procedures:

Step 1: Create new Java file, name as MembershipRequirement.java.


Step 2: Rewrite the following program code and save.

Step 3: Build and run the code to observe the output.


Step 4: In your opinion, what is the compound-relational test?

37
Activity 5F (CLO2)
Activity Outcome: Write a program to demonstrate Nested-if statement

Students are required to write a program named MembershipDiscount.java that can determined the
discount rate based on their membership period by year.

Membership Period Discount Rate


(year) Entitled (%)
1-3 10
4-6 20
7-9 30
10 and above 40
Procedures:
Step 1: Create new Java file, name as MembershipDiscount.java.
Step 2: Rewrite the following program code and save.

38
Step 3: Build and run the code to observe the output.

Step 4: Insert the following bold snippet code according to guideline below in the
MembershipDiscount.java file

for (int i = 0; i<4; i++){


System.out.println("Please enter how many years you have become
member:\n");
....
else
{
System.out.println("You are not a member yet\n");
}
}

Step 5: Write down the changes that you have observed once you run the program.

Activity 5G (CLO2)
Activity Outcome: Write a program to demonstrate Switch Statement

Students are required to create a java program named as SwitchPaymentMethod.java that


demonstrates the use of Switch Statement.

Procedures:
Step 1: Create new Java file, name as SwitchPaymentMethod.java.
Step 2: Rewrite the following program code and save.

39
Step 3: Build and run the code to observe the output.

40
Activity 5H (CLO2)
Activity Outcome: Write program using looping structures (while, do..while, for statements)

Programs below illustrate looping structures to print the output:

Output:

Im clever
Im clever
Im clever
Im clever
Im clever

i. while loops

Procedures:

Step 1: Open a new text file, and then enter the above code.
Step 2: Observer the output. Try to understand its.

ii. do..while loops

41
Procedures:
Step 1: Open a new text file, and then enter the above code.
Step 2: Observer the output. Try to understand its.

iii. for loops

Procedures:
Step 1: Open a new text file, and then enter the above code.
Step 2: Observer the output. Try to understand its.
Step 3: Make a conclusion, for every loop programs that you have observer.

Conclusion:

Activity 5I (CLO2)
Activity Outcome: Program oddNo.java below illustrates the working of a while loop.

42
Procedures:

Step 1: Write the program above in notepad and save. The filename is oddNo.java.
Step 2: Fill in the blanks in line 7 and 10 such that the output of the program is 1 3 5 7 9 11
Step 3: Save, compile and run the program to observe the output.

Output:

Activity 5J (CLO2)

Activity Outcome: Program count_1.java below illustrates the working of a do-while loop.

Procedures:
Step 1: Write the program above in notepad and save. The filename is count_1.java.

Step 2: Fill in the blanks with appropriate code to increment the variable count.

Step 3: Save, compile and execute the code. What is the output?

Output:

43
Activity 5K (CLO2)
Activity outcome: The program LoopDemo.java below illustrates the working of for loop.

Procedures:

Step 1: Write the program above in notepad and save. The filename is LoopDemo.java.
Step 2: Save, compile and execute the code. What is the output?

Output:

44
Reflection:

I can understand selection statements. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand looping statements. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can differentiate between nested if and switch case. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

45
LAB 6: Arrays

Learning Outcomes

This Lab sheet encompasses 4 activities (Activity 6A, 6B, 6C and 6D).

By the end of this laboratory session, you should be able to:


1. Create reference array of objects
2. Declare and initialize an array
3. Pass array to methods
4. Return array to methods
5. Write program using single and multidimensional array

Hardware/Software: Computer with JDK latest version.

Activity 6A (CLO2)

Activity Outcome: Create reference array of objects.

All the Java primitive types have well-defined standard sizes, so all primitive values can be stored in a
fixed amount of memory (between one and eight bytes, depending on the type).

But classes and array types are composite types; objects and arrays contain other values, so they do not
have a standard size, and they often require quite a bit more memory than eight bytes. For this reason,
Java does not manipulate objects and arrays directly. Instead, it manipulates references to objects and
arrays. Because Java handles objects and arrays by reference, classes and array types are known as
reference types.

Procedures:

Step 1: Write the following program and save it as TestArray.java.

Step 2: Compile and run the program.

46
Step 3: Observe the output.

Output:

Step 4: Amend the program by adding the following statement before the last statement.
studentArray[0] = new Student();

Step 5: Recompile the program and run it.


Step 6: Observe the output.
Output:

Activity 6B (CLO2)
Activity Outcome: Declare and initialize primitive type array.

An array in Java is a type of object that can contain a number of variables. These variables can be
referenced only by the array indexa non-negative integer. The first element in an array has an index of
0.

All of these contained variables, or elements, must be the same type, which is the type of the array. Every
array has an associated length variable, established when the array is created, which you can access
directly. If you try to address an element with an index that is outside the range of the array, an exception
is generated.

Procedures :

Step1: Write the following program and save it as TestArray2.java.

Step 2: Compile and run the program.

47
Step 3: Observe the output.

Output:

Step 4: Delete the declaration and initialization statements in the program. Replace it with the following
statements:
int a[]={10,20,70,40,50};

Step 5: Rebuild and run the program.


Step 6: Observe the output.

Output:

Activity 6C (CLO2)

Activity Outcome: Pass and return array to methods.


An example to get minimum number of an array using method.

Procedures:
Step 1: Write the following program and save it as TestArray3.java.

48
Step 2: Compile and run the program.

Step 3: Observe the output.

Output:

Step 4: Write the following program and save it as TestArray4.java

Step 5: Compile and run the program.

Step 6: Observe the output.

Output:

49
Activity 6D (CLO2)
Activity Outcome: Write program using single and multidimensional array

An example to declare, instantiate, initializes and prints the 2 Dimensional arrays.

Procedures:
Step 1: Write the following program and save it as TestArray5.java.

Step 2: Compile and run the program.

Step 3: Observe the output.

Output:

50
Reflection:

I can understand arrays. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand looping statements in array. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can differentiate between 1-dimensional array and 2-dimensional array. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

51
LAB 7: Classes, Inheritance and Polymorphism

Learning Outcomes
This Lab sheet encompasses 6 activities (Activity 7A until 7F).

By the end of this lab, students should be able to:


Write methods in Java programs
Create an object in Java programs
Pass parameters by value to methods in Java programs
Implement constructor and constructor overloading in Java programs.
Implement method overloading in Java Programs.
Explain data field encapsulation in Java programs

Activity 7A (CLO2)

Activity Outcome: Illustrates how to create a method

Procedure:

Step 1: Program below is an example of explaining method creation

// Program explaining method creation


class Act7a
{
public static void main(String args[])
{
wish(); //calling the function wish()
}

static void wish() //function or method definition


{
System.out.println("Good Morning");
}
}

Step 2: Type the programs given below. Save the program as Act7a.java

Step 3: Compile and run the program. Observe the output.

52
Activity 7B (CLO2)

Activity Outcome: Illustrates how to create an object for Act6b class and to access its method.

Procedure:
Step 1: Type the programs given below

// Program explaining class creation


class Act7b
{
String name, int age;

void insert(String n, int a)


{
name = n;
age = a;
}

void show()
{
System.out.println(My Name is + name);
System.out.println(My Age is + age);
}

public static void main(String[]args)


{
Act7b obj = new Act7b();
obj.insert(Zaida, 20);
obj.show();
}
}

Step 2: Save the program as Act7b.java


Step 3: Compile and run the program. Observe the output.

53
Activity 7C (CLO2)

Activity Outcome: Illustrates how to create a method and call it from main method

Procedure:

Step 1: Type the programs given below

class Student
{
void show()
{
System.out.println (Hi, Good Morning);
}
}

class Act7c
{
public static void main(String args[])
{
Student obj = new Student();
obj.show();
}
}

Step 2: Save the program as Act7c.java

Step 3: Compile and run the program. Observe the output.

54
Activity 7D (CLO2)

Activity Outcome: Understand and implement Method Overloading

Procedure:
Step 1: Add the highlighted codes into Activity 7C.

class Student
{
void show()
{
System.out.println (Hi, Good Morning);
}

void show(String name, int age)


{
System.out.println(My Name is + name);
System.out.println(My Age is + age);
}
}
class Act7d
{
public static void main(String args[])
{
Student obj = new Student( );
obj.show();
obj.show (Dhia,24);
}
}

Step 2: Save the program as Act7d.java


Step 3: Compile and run the program. Observe the output.

Activity 7E (CLO2)

Activity Outcome: Understand and create constructor.

Procedure:
Step 1: Type the programs given below

class Cons
{
Cons()
{
System.out.println (Im automatically called immediately when the
object is created before the new operator completes its job);
}
}
class Act7e
{
public static void main(String args[])
{
Cons obj = new Cons();
}
}
Step 2: Save the program as Act7e.java
Step 3: Compile and run the program. Observe the output.

55
Activity 7F (CLO2)

Activity Outcome: Understand and create constructor overloading.

Procedure:
Step 1: Add the highlighted codes into Activity 7E.

class Cons
{
Cons()
{
System.out.println (Im automatically called immediately when
the object is created before the new operator completes its
job);
}

Cons(String message)
{
System.out.println(Constructor Overloading + message);
}
}

class Act7f
{
public static void main(String args[])
{
Cons obj = new Cons();
Cons obj = new Cons(Yes, I got it!);
}
}

Step 2: Save the program as Act7f.java


Step 3: Compile and run the program. Observe the output.

56
Reflection:

I can understand about object in java programs. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand about method in java programs. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can define constructor in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

57
LAB 8: Classes, Inheritance and
Polymorphism
Learning Outcomes
This Lab sheet encompasses 12 activities (Activity 8A until 8L).

By the end of this lab, students should be able to:


Write Java program using String and StringBuffer objects.
Convert a String to a primitive data in Java programs.
Construct program using method in class String.
Create packages in Java Program

Activity 8A (CLO2)

Activity Outcome: Demonstrates the String class constructors.

Procedure:
Step 1: Type the following program.

public class Act8A


{
public static void main(String args[])
{
char charArray[] = {b,i,r,t,h,d,a,y};
StringBuffer sb;
String s1,s2,s3,s4, output;
s1 = new String (Hello);
sb = new StringBuffer (Welcome to Java Programming);

//Use String constructors


s2 = new String (s1);
s3 = new String (charArray);
s4 = new String (sb);

//append Strings to output


output = s1 = + s1 + \ns2 = + s2 + \ns3 = + s3 +
\ns4 = + s4 + \ns4 = + s4 + \ns5 = + s5;
System.out.println(output);
}
}

Step 2: Compile and execute the above program.

Step 3: Describe the output.

58
Activity 8B (CLO2)

Activity Outcome: Demonstrates the length(), charAt() and getChars() method of the String class.

Procedure:
Step 1: Type the following program.

public class Act8B


{
public static void main(String args[])
{
String s1;
char chararray[];
s1=new String(Hello there!);
charArray= new char [5];
System.out.println (s1 : + s1);
System.out.println (Length of s1 : + s1.length());
System.out.println (Character at 3rd position :
+s1.charAt(2));
s1.getChars(0,5,charArray,0);
System.out.print(The character array is : );
for(int i=0;i<charAray.length;i++)
System.out.print( + charArray[i]);
System.out.println();
}
}

Step 2: Compile and execute the above program.


Step 3: Describe the output.

59
Activity 8C (CLO2)

Activity Outcome: Demonstrates the methods equals(), compareTo() of the String class

Procedure:
Step 1: Type the following program.

public class Act8C


{
public static void main(String args[])
{
String s1,s2,s3;
s1=new String(Hello);
s2=new String(Good Bye);
s3=new String(Happy Birthday);
System.out.println(s1 = + s1+\ns2 = + s2+ s3 = + s3);

//Test for equality


if (s1.equals(Hello)
System.out.println(s1 equals \Hello\ );
else
System.out.println(s1 does not equal \Hello\ );

//Test for equality with == operator


if (s1==Hello)
System.out.println(s1 equals \Hello\ );
else
System.out.println(s1 does not equal \Hello\ );

//Test compareTo
System.out.println(s1 compare to \Hello\ is
+s2.compareTo(Hello));
System.out.println(s2 compare to s3 is + s2.compareTo(s3));
}
}

Step 2: Compile and execute the above program.

Step 3: Describe the output.

60
Activity 8D (CLO2)
Activity Outcome: Demonstrates the String class index methods

Procedure:
Step 1: Type the following program .

public class Act8D


{
public static void main(String args[])
{
String letters=This is a test;
int value1, value2, value3, value4;
value1=letters.indexOf(s);
System.out.println(First occurrence of \s\ in a string +is at
index : +value1);
value2=letters.indexOf(is);
System.out.println(First occurrence of \is\ in a string +is
at index : +value2);
value3=letters.lastIndexOf(s);
System.out.println(The last occurrence of \s\ in a string +is
at index : +value3);
value4=letters.lastIndexOf(is);
System.out.println(The last occurrence of \s\ in a string +is
at index : +value4);
}
}

Step 2: Compile and execute the above program.

Step 3: Describe the output.

61
Activity 8E (CLO2)
Activity Outcome: Demonstrates the String class substring methods.

Procedure:
Step 1: Type the following program.

public class Act8E


{
public static void main(String args[])
{
String s1=I do shopping in Mega Mall;
String s2=s1.substring(5,12);
String s3=s1.substring(17);
System.out.println(substring from index 5 to 12 is : +s2);
System.out.println(substring from index 17 to end is : +
s3);
}
}

Step 2: Compile and execute the above program.

Step 3: Differentiate the substring method operation.

Activity 8F (CLO2)
Activity Outcome: Demonstrates the String class concat method.

Procedure:
Step 1: Type the following program.

public class Act8F


{
public static void main(String args[])
{
String s1= new String(Happy );
String s2=new String(Birthday);
System.out.println(Result after concatenation process : +
s1.concat(s2));
}
}

Step 2: Compile and execute the above program.

Step 3:State the output.

62
Activity 8G (CLO2)

Activity Outcome: Demonstrates StringBuffer constructors.

Procedure:
Step 1: Type the following program.

public class Act8G


{
public static void main(String args[])
{
StringBuffer bf1, bf2,bf3;
bf1= new StringBuffer();
bf2= new StringBuffer(10);
bf3= new StringBuffer(PoliteknikUngku Omar);
System.out.println(Buffer 1 : \ + bf1.toString()+ \);
System.out.println(Buffer 1 : \ + bf2.toString()+ \);
System.out.println(Buffer 1 : \ + bf3.toString()+ \);
}
}

Step 2: Compile and execute the above program.

Step 3: Differentiate the various type of StringBuffer constructors.

Activity 8H (CLO2)
Activity Outcome: Demonstrates the length() and capacity() methods of the StringBuffer class.

Procedure:
Step 1: Type the following program.

public class Act8H


{
public static void main(String args[])
{
StringBuffer bf = new StringBufffer(Hello, how are you?);
System.out.println(Buffer + bf.toString() + \nlength =
+bf.length()+ \ncapacity = +bf.capacity());
bf.ensureCapacity(75);
System.out.println(\n\nNew Capacity = + bf.capacity());
bf.setLength(10);
System.out.println(New length = + bf.length() +
\n Buffer : +bf.toString());
}
}

63
Step 2: Compile and execute the above program.
Step 3: Explain the ensureCapacity() and setLength() methods.

Activity 8I (CLO2)
Activity Outcome: Demonstrates the charAt(), setCharAt(), getChars(), and
reverse methods of class StringBuffer

Procedure:
Step 1: Type the following program .

public class Act8I


{
public static void main(String args[])
{
StringBuffer bf=new StringBuffer(hello there!);
System.out.println(Buffer : + bf.toString()+
\nCharacter at 0 : +
bf.charAt(0)+\nCharacter at 4 : + bf.charAt(4));
char charArray[]=new char[bf.length()];
bf.getChars(0,bf.length(), charArray,0);
System.out.print(\n\nThe characters are:);
for(int i=0;i<charArray.length;i++)
System.out.print(charArray[i]);
bf.setCharAt(0,H);
bf.setCharAt(0,T);
System.out.print(\nBuffer : + bf.toString());
bf.reverse();
System.out.print(\nBuffer : + bf.toString());
}
}

Step 2: Compile and execute the program.

Step 3: State the output

64
Activity 8J (CLO2)
Activity Outcome: Demonstrates the append() methods of the StringBuffer class.

Procedure:
Step 1: Type the following program.

public class Act8J


{
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer (Welcome to beautiful);
sb1.append (Eye on Malaysia);
System.out.println(sb1);
}
}

Step 2: Compile and execute the above program.

Step 3: State the output

Activity 8K (CLO2)
Activity Outcome: Convert a String to a primitive data in Java programs.

Procedure:
Step 1: Type the following program.

import java.io.*;
class Act8K
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
String str;
int num; // declares an int variable
System.out.println("Enter an integer:");
str = stdin.readLine();
num = Integer.parseInt(str);
System.out.println("Integer Value: "+num);
}
}

Step 2: Compile and execute the above program.


Step 3: State the output

65
Activity 8L (i) (CLO2)

Activity Outcome: Demonstrate how to create a package in Java program

Procedure:
Step 1: Declare the package in the first line of the source file. Package name must be in lowercase letter.
Step 2: Declare the class as public, so that it can be used in other packages.
Step 3: Define the methods of the class.
Step 4: Create a subdirectory under the current directory.
Step 5: Name the subdirectory same as the package name.
Step 6: Store the source file in the subdirectory.
Step 7: Compile the file. This file creates .class file in the subdirectory.

Activity 8L (ii) (CLO2)

Activity Outcome: Declare the package and definition of the class in the package.

Procedure :
Step 1: Create a subdirectory pack1 in the current directory.
Step 2: Save the program as Class1.java in the pack1 subdirectory. For example if d:\ is the current
directory, then create d:\pack1and save Class1.java in it.

package pack1;
public class Class1
{
public void show ()
{
int x,y,result;
x=10;
y=5;
result=x*y;
System.out.println ("The result is "+result);
}
}

Step 3: Compile the program and save it the pack1 subdirectory.

Activity 8L (iii) (CLO2)

Activity Outcome: Demonstrate how to import class from the created package

Procedure:

Step 1: Save the program as packtest.java in the current directory.


Step 2: If d: is the directory in which the packtest.java is and the user-defined package is in d:\pack1,
then set the classpath as set CLASSPATH=%CLASSPATH%;d:\pack1; in the current
directory. Type the above command in the command prompt and execute it to set the path.

66
import pack1.Class1;
class Packtest1
{
public static void main(String args[])
{
Class1 c1 = new Class1();
c1.show();
}
}

Step 3: Compile and run the program.

Reflection:

I can understand about string in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand about string buffer in java programs. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand method in string class. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

67
LAB 9: Classes, Inheritance and
Polymorphism
Learning Outcomes
This Lab sheet encompasses 5 activities (Activity 9A, 9B, 9C, 9D and 9E).

By the end of this lab, students should be able to:


Apply keyword super in Java program
Implement Overriding method in Java program

Activity 9A (CLO2)

Activity Outcome: Define Super and usage of super keyword in Java Code

Briefly explain in your own words the definitions below.

Super

Usage of Super keyword

68
Activity 9B (CLO2)

Activity Outcome: Apply Super keyword in java code

Rewrite the program bellow, used super keyword to distinguish between parent class instance variable
and current class instance variable.

1. class Vehicle{
2. int speed=50;
3. }
4. class Bike3 extends Vehicle{
5. int speed=100;
6. void display(){
7. System.out.println(speed);
8. }
9. public static void main(String args[]){
10. Bike3 b=new Bike3();
11. b.display();
12. }
13. }

Rewrite the program bellow, used super keyword to invoke the parent class constructor

1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike5 extends Vehicle{
6. Bike5(){
7. System.out.println("Bike is created");
8. }
9. public static void main(String args[]){
10. Bike5 b=new Bike5();
11.
12. }
13. }

69
Activity 9C (CLO2)

Activity Outcome: Syntax overriding method

Briefly explain in your own words the definitions below .

Method Overriding

Activity 9D (CLO2)
Activity Outcome: Illustrates Method Overriding in java

Procedure:

Step 1: Type the following code


Step 2: Save the program
Step 3: Compile and execute the program
Step 4: Write the output

class Sum
{
int n;

void add (int num) // add method in super class


{
int resul t = 0;
this.n = num;
for (int i=1; i<=n; i++)
result = result + i;
System.out.println("The sum is " +result);
}
}

class Even extends Sum


{
void add (int num) // add method in subclass
{
int result = 0;
this.n = num;
for (int i=2; i<=n; i+=2)
result = result + i;
System.out.println("The sum is " +result);
}
}

70
class Act9D
{
public static void main (String args[])
{
Sum obj1 = new Sum();
Even obj2 = new Even();
obj1.add(10); // calling the Add method of super class
obj2.add(10); // calling the Add method of sub class
}
}

Activity 9E (CLO2)

Activity Outcome: Implement overriding method in java code

Write a java program to perform the concept of method overriding for calculating simple interest of 3
banks A,B,C. using dynamic method dispatchBank As rate of interest-10%, Banks B rate of interest-9%,
BankC rate of interest -7%.

Reflection:

I can understand about keyword super in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand about overriding method in java programs. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

71
ACTIVITY 10: Classes, Inheritance and
Polymorphism
Learning Outcomes
This Lab sheet encompasses 3 activities (Activity 10A, 10B and 10C).

By the end of this lab, students should be able to:


Apply Polymorphism in Java program

Activity 10A (CLO2)


Activity Outcome: Define Polymorphism

Briefly explain in your own words the definitions below.

Polymorphism

Activity 10B (CLO2)

Activity Outcome: Implement polymorphism in Java Code.

Consider a scenario given:-


Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according
to banks. For example, BSN, CIMB and RHB banks could provide 8%, 7% and 9% rate of interest. Write
the code based the Class Diagram.

72
BANK

getRateofInterest( ) : int

BSN CIMB RHB

getRateofInterest( ) : int getRateofInterest( ) : int getRateofInterest( ) : int

73
Activity 10C (CLO2)

Activity Outcome: Implement polymorphism in Java Code.

Write a program to create a class named shape. In this class we have two sub classes rectangle, and
triangle. All the shapes must have a method called getArea(), which returns the area of that particular
shape. Write the code based the Class Diagram and Shape.java bellow:-

Output:
Rectangle of length=4 and width=5,
subclass of Shape of color="red"
Area is 20.0

Triangle of base=4 and height=5,


subclass of Shape of color="blue"
Area is 10.0

Shape.java

public class Shape {

private String color;

// Constructor
public Shape (String color) {
this.color = color;
}

public String toString() {


return "Shape of color=\"" + color + "\"";
}

public double getArea() {


System.err.println("Shape unknown! Cannot compute area!");
return 0; }
}

74
Reflection:

I can understand about polymorphism in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

75
LAB 11: Classes, Inheritance and
Polymorphism

Learning Outcomes

This Lab sheet encompasses 6 activities (Activity 11A, 11B, 11C, 11D,11E and 11F).

By the end of this tutorial session, you should be able to:

Implement abstract classes in Java program


Classify the built-in interface class in Java Program
Create Java program using following classes:
Implementing interface

Activity 11A (CLO2)

Briefly explain abstract class in Java programs.

Abstract Class

76
State the rules to create abstract class and method

Rules of Abstract Class and Method

Activity 11B (CLO2)

Activity Outcome: Illustrates the use of Abstract classes in java

Procedure:
Step 1: Type the following code
Step 2: Save the program
Step 3: Compile and execute the program
Step 4: Write the output

abstract class Arithmetic


{
int a,b;
abstract void calc();
}

class Add extends Arithmetic


{
void calc()
{
System.out.println(The sum is + (a+b));
}
}

class Sub extends Arithmetic


{
void calc()
{
System.out.println(The difference is + (a-b));
}
}

77
class Abst
{
public static void main (String args[])
{
Add obj1 = new Add();
obj1.a = 10;
obj1.b = 6;
obj1.calc();
Sub obj2 = new Sub();
obj2.a = 10;
obj2.b = 6;
obj2.calc();
}
}

Activity 11C (CLO2)

Activity Outcome: Illustrates the use of Abstract classes in java

Procedure :

Step 1: Key-in below program.

Bike12.java

class Bike12{
abstract void run();
}

Step 2 : Observe the output.

Output:

Step 3: How to correct the above error?

Correct error above.

78
ACTIVITY 11D (CLO2)

The following example illustrates the use of Abstract classes in java

Procedure :
Step 1: Type the following code
Step 2: Compile the program
Step 3: Identify the missing syntax and correct them
Step 4: Save the program
Step 5: Compile and execute the program
Step 6: Write the output

abstract class Shape{ // abstract class


abstract void draw(); // abstract method
}

class Rectangle extends Shape{ //sub class Rectangle


void draw(){System.out.println("drawing rectangle");}
// Abstract method implemented in a subclass
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
// Abstract method implemented in a subclass
}

class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
}
}

Output:

Activity 11E (CLO2)

Activity Outcome: Demonstrates the implement of polymorphism and interface in Java Program.

Procedure:
Step 1: Type the following program.

79
interface Person
{
public String getName();
}

class Student implements Person


{
String name="Qistina";

public String getName()


{
System.out.println("Student Name:" + name);
return name;
}
}

class Employee implements Person


{
String name="Amirul";

public String getName()


{
System.out.println("Employee Name:" + name);
return name;
}
}

public class Act9B


{
public static void main( String[] args )
{
String temp;

Student studentObject = new Student();


Person ref= studentObject;
Person ref2 = new Student();

Employee employeeObject = new Employee();


Person ref3 = employeeObject;
Person ref4 = new Employee();

System.out.println ("getName() method of Student class is


called");
temp= ref.getName();
System.out.println( temp );
ref = employeeObject; /*Person ref. points to an Employee
object*/
System.out.println("getName() method of Employee class is
called");
temp = ref3.getName();
System.out.println( temp );
}
}

Step 2: Compile and execute the program


Step 3: Write the output

80
Activity 11F (CLO2)

Activity Outcome Create Java program using implementing interface

Procedure:
Step 1: Type the following program.

// File name : Animal.java

interface Animal {

public void eat ( );


public void trave ( );
}

Step 2: Save the program as Animal.java


Step 3: Open new notepad. Type the following program.

// File name : MammalInt.java

public void eat ( ) {


System.out.println (Mammal eats);
}

public void travel ( ) {


System.out.println(Mammal travels);
}

public int noofLegs ( ) {


Return 0;
}

public static void main (String args[ ]) {


MammalInt m = new MammalInt ( );
m.eat ( );
m.travel ( );
}

Step 2: Compile and execute the program


Step 3: Write the output

81
Reflection:

I can understand about abstract class in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand about interface in java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

82
LAB 12: Multithreading and Exception
Handling

Learning Outcomes:

This activity encompasses 5 activities. (Activity 12A, 12B, 12C, 12D and 12E)

By the end of this laboratory session, you should be able to:


1. Write multithreaded application

Activity 12A (CLO2)

Activity Outcome : Create and start a thread by extending Thread class.

Procedures:
Step 1: Open Notepad and type the following code:

class MultithreadingDemo extends Thread {


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}

Step 2: Save, compile and run the program. Save the program as MultithreadingDemo.java.
Observe the output.

83
Activity 12B (CLO2)
Activity Outcome : Create and start a thread by implementing Runnable interface.

Procedures:
Step 1: Open Notepad and type the following code:

class MultithreadDemo implements Runnable{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadDemo obj=new MultithreadDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}

Step 2: Save, compile and run the program. Save the program as MultithreadDemo.java.
Observe the output.

Activity 12C (CLO2)


Activity Outcome : Performing two task by two threads.

Procedures:
Step 1: Open Notepad and type the following code:

class Thread1 extends Thread{


public void run(){
System.out.println(" This is task one");
}
}

class Thread2 extends Thread{


public void run(){
System.out.println("This is task two");
}
}

84
class TestMultitasking{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();

t1.start();
t2.start();
}
}

Step 2: Save, compile and run the program. Save the program as TestMultitasking.java.
Observe the output.

Activity 12D (CLO2)


Activity Outcome : Performing three threads with a method sleep().

Procedures:
Step 1: Open Notepad and type the following code:

class ThreadTest extends Thread {


public ThreadTest(String str) {
super(str);
}

public void run() {


for (int i = 0; i < 5; i++) {
System.out.println("Loop " + i + ": " + getName());
try {
sleep((int) (Math.random() * 2000));
} catch (InterruptedException e) {
}
}
System.out.println("Test Finished for: " + getName());
}
}

85
public class Test {

public static void main(String args[]) {


new ThreadTest("Thread eBay").start();
new ThreadTest("Thread Paypal").start();
new ThreadTest("Thread Google").start();
}
}

Step 2: Save, compile and run the program. Save the program as Test.java. Observe the output.

Activity 12E (CLO2)


Based on Activity 12D, give the explanation for code execution.

86
Reflection:

I can understand the concept of multithreading. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand the use of multithreading in Java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

87
LAB 13: Multithreading and Exception
Handling

Learning Outcomes:

This Lab sheet encompasses 6 activities (Activity 13A, 13B, 13C, 13D, 13E and
13F).

By the end of this laboratory session, you should be able to:

1. Understand concept of exception handling.


2. Create Java programs using exception handling.

Hardware/Software: Computer with JDK latest version.


ACTIVITY 13A (CLO2)

Activity Outcome : The program below illustrate the concept of NumberFormatException

Procedure :
Step 1: Type the following code
Step 2: Save the program as ConvertStringToNumber.java
Step 3: Compile and execute the program

public class ConvertStringToNumber


{
public static void main(String[] args)
{
try
{
String s = "FOOBAR";
int i = Integer.parseInt(s);
// this line of code will never be reached
System.out.println("int value = " + i);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
}

Step 4: Write and observe the output


Output:

88
ACTIVITY 13B

Activity Outcome : The following example illustrates the concept of ArrayIndexOutOfBoundsException

Procedure :
Step 1: Type the following code
Step 2: Save the program as ArrayExcepDemo.java
Step 3: Compile and execute the program
Step 4: Write and observe the output

class ArrayExcepDemo
{
public static void main(String args[])
{
int var[]={5,10};
try
{
int x = var[2]-var[1];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array subscript out of range");
}
}
}

Output:

89
ACTIVITY 13C (CLO2)

Activity Outcome : The following example illustrates the concept the concept of ArithmeticException

Procedure :

Step 1: Type the following code


Step 2: Save the program as ArrayExcepDemo.java
Step 3: Compile and execute the program
Step 4: Write and observe the output

class excep1
{
public static void main(String args[])
{
int A,B,C=0;
A=Integer.parseInt(args[0]);
B=Integer.parseInt(args[1]);
try
{
C= A/B;
}
catch(ArithmeticException ae)
{
System.out.println("Caught Exception :- " + ae.getMessage());
}
System.out.println("The Value of C:- " + C);
}
}

Output:

90
ACTIVITY 13D
Activity outcome : Understand the concept of Multiple Catch

Procedures :

Step 1: Type the following code


Step 2: Save the program as MultiCatchDemo.java
Step 3: Compile and execute the program
Step 4: Write and observe the output

class MultiCatchDemo
{
public static void main(String args[])
{
int a=10,b=0,c=0;
int arr[]={10,20};
try
{
c=a/b;
int var = arr[2]-arr[1];
}
catch (ArithmeticException ae)
{
System.out.println("Arithmetic exception due to division by
zero");
System.out.println("Change b value and execute");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("ArrayIndexOutBoundsException as index not in
range is used");
}
}
}

Output:

91
ACTIVITY 13E (CLO2)
Activity outcome : Understand the use of throw statement.

Procedures :

Step 1: Type the following code


Step 2: Save the program as throwDemo.java
Step 3: Compile and execute the program
Step 4: Write and observe the output

class throwdemo
{
public static void main(String args[])
{
int x=4;
int y=2;
float z=0 ;
try
{
z = (float)x/(float)y;
if(z<0.01)
throw new Exception("Number is too small");
}
catch(Exception e)
{
System.out.println("Caught the exception:- " + e.getMessage());
}
System.out.println("The value of z:- " + z);
}
}

Output:

92
ACTIVITY 13F
Activity outcome : Understand the use of finally blocks

Procedures :

Step 1: Type the following code


Step 2: Save the program as finallyDemo.java
Step 3: Compile and execute the program
Step 4: Write and observe the output

class finallydemo
{
public static void main(String args[])
{
int a=0,b=5,c=0;
try
{
c=b/a;
}

catch(ArithmeticException e)
{
System.out.println("I will execute if the exception is generated");
}
finally
{
System.out.println("I always execute at last");
}
}
}

Output:

93
Reflection:

I can understand the concept of exception handling. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

I can understand the use of exception handling in Java program. Explain.

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

________________________________________________________________________________

94

S-ar putea să vă placă și