LKAT Object Oriented Programming
LKAT Object Oriented Programming
(LABORATORY EXERCISES)
TOPICS PAGES
Introduction to Object Oriented
LAB 1
Programming
Introduction to Object Oriented
LAB 2
Programming
LAB 6 Arrays
This Lab sheet encompasses 5 activities. (Activity 1A, 1B, 1C, 1D and 1E)
Activity 1A (CLO1)
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.
2
Class name
Object, arttributes,properties
Method,function,behaviour
Activity 1B (CLO1)
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.
3
Class name
variable
function
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:
a.
5
b.
c.
6
Activity 1E (CLO1)
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:
7
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.
Encapsulation
Data
Abstraction
Inheritance
Polymorphism
Reflection:
_________________________________________________________________________
_________________________________________________________________________
_________________________________________ ________________________________
_________________________________________________________________________
_________________________________________________________________________
8
I can explain the basic terminologies of OOP. Explain.
_________________________________________________________________________
_________________________________________________________________________
________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
________________________________________________________________________ _
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
____________________________________________________ _____________________
_________________________________________________________________________
9
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
Activity 2A (CLO1)
10
Activity 2B (CLO2)
Assume that you’re 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.
11
Step 3: Illustrate using Class Diagram
Answer :
Step 4: Type a program based on the above Class Diagram in java programming languages.
Answer :
12
Activity 2C (CLO1)
void displayData() Z
function
{
System.out.println("Book Name:"+book_name);
13
Reflection:
_________________________________________________________________________
_______________________________________________ __________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
I can identify the components of UML class diagram. Draw and explain.
_________________________________________________________________________
_________________________________________________________________________
_______________________________________________ _________________________
_________________________________________________________________________
_________________________________________________________________________
________________________________________________________________________ _
_________________________________________________________________________
_________________________________________________________________________
___________________________________________________________________ ______
_________________________________________________________________________
14
_________________________________________________________________________
Learning Outcomes:
This lab sheet encompasses 10 activities (Activity 3A, 3B, 3C, 3D, 3E, 3F, 3G, 3H, 3I and 3J).
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).
15
Activity 3B (CLO2)
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. }
Activity 3C (CLO2)
Procedure:
Step 1: Open Notepad and type the following code:
16
/* Activity 3C */
class Act3C // define class
name
{ // open curly brace the beginning of class block
Step 2: Save, compile and run the program. Save the program as Act3C.java. Write the output in the
area below.
Output:
Activity 3D (CLO2)
Procedure:
Step 1: Open Notepad and type the following code:
17
/* Activity 3D */
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:
18
Step
/* Activity 3E */ 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:
19
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
{
Output:
20
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
{
}
}
Program:
Activity 3I (CLO2)
Procedures :
Step 1 : Open Notepad and type the following code:
21
/* 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)
Procedures :
/* 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:
22
Reflection:
______________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
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.
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
23
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
Activity 4A (CLO2)
Procedure:
Step 1: Open Notepad and type the following code:
class Act4A
{ public static void main(String[]
args){
short numberS = 3;
24
// declare variable numberI as integer, initialized 65 value to it
int numberI = 65;
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)
Procedure:
Step 1: Open Notepad and type the following code:
25
class Act4B
{ public static void main(String[]
args)
{
//declare variables radius as int, initialized value 3 to radius. int
radius=3;
Output:
Activity 4C (CLO2)
The following program uses primitive data type of byte and short:
Procedures:
Step 1: Open Notepad and type the following code:
26
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 value’s from 127 to 128. Step
4: Compile and run the program. Observe the output.
Output:
Step 5: Change the value variable value’s 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:
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
27
{ 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 value’s 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 value’s to double. Compile and run the program. Is there a
difference? Explain.
Output:
Explanation:
_______________________________________________________________________________
_______________________________________________________________________________
Step 6: Change the value of constant value’s from 3.4E038F to 1.7e308D. Step
7: Compile and run the program. Observe the output.
Output:
Explanation:
_______________________________________________________________________________
_______________________________________________________________________________
28
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;
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.
29
Procedures:
Step 1: Open Notepad and type the following code:
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);
Step 2: Save, compile and run the program. Save the program as Act4F.java. Observe the output.
Output:
30
Activity 4G (CLO2)
Procedures:
Step 1: Open Notepad and type the following code:
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;
31
int numI2 = (int) numF1;
Step 2: Save, compile and run the program. Save the program as Act4G.java. Observe the output.
Output:
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:
32
//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
Step 2: Save, compile and run the program. Save the program as Act4H.java. Observe the output.
Output:
Activity 4I (CLO2)
33
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:
class Act4I
{
public static void main (String[] args) throws IOException
{
BufferedReader inData = new BufferedReader(new
InputStreamReader(System.in));
//declare variable
String str;
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:
34
Step 1: Open Notepad and type the following code:
//declare variable
String str;
String num1, num2, num3;
int number1, number2,
number3;
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.*/
36
}//end class
Step 2: Save, compile and run the program. Save the program as Act4K.java. Observe the output.
Output:
Reflection:
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What ______________________________________________________I have learnt from all the
activities above? (Write in your own word below)__________________________
________________________________________________________________________________
________________________________________________________________________________
37
________________________________________________________________________________
________________________________________________________________________________
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
38
3. Do..while
39
(CLO2)
: Write a program to demonstrate
Activity 5A
Procedures:
Step 1: Open Notepad and type the following code:
class Act5A
{ public static void main(String[] args)
{
Step 2: Save, compile and run the program. Save the program as Act5A.java. Observe the output.
Activity 5B (CLO2)
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.");
40
}
}
Step 2: Save, compile and run the program. Save the program as Act5B.java. Observe the output.
Activity 5C (CLO2)
Procedures:
Step 1: Open Notepad and type the following code:
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;
41
(CLO2)
: Write a program to demonstrate
default:
System.out.println("Invalid input");
}
}
}
Step 2: Save, compile and run the program. Save the program as Act5C.java. Observe the output.
Activity 5D
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:
42
Step 3: Build successful the program and run to see the output. Step
4: Write the output in the box below.
43
(CLO2)
: Write a program to demonstrate
Activity 5E
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:
44
Activity 5F
Students are required to write a program named MembershipDiscount.java that can determined the
discount rate based on their membership period by year.
45
(CLO2)
: Write a program to demonstrate
Step 4: Insert the following bold snippet code according to guideline below in the
MembershipDiscount.java file
46
for (int i = 0; i<4; i++){
System.out.println("Please enter how many years you have become
member:\n"); .... else
Step 5: Write down the changes that you have observed once you run the program.
Activity 5G (CLO2)
Procedures:
Step 1: Create new Java file, name as SwitchPaymentMethod.java. Step
2: Rewrite the following program code and save.
47
Step 3: Build and run the code to observe the output.
48
Activity 5H (CLO2)
Activity Outcome: Write program using looping structures (while, do..while, for statements)
Output:
I’m clever
I’m clever
I’m clever
I’m clever
I’m 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 it’s.
49
Procedures:
Step 1: Open a new text file, and then enter the above code. Step
2: Observer the output. Try to understand it’s.
Procedures:
Step 1: Open a new text file, and then enter the above code.
Step 2: Observer the output. Try to understand it’s.
Step 3: Make a conclusion, for every loop programs that you have observer.
Conclusion:
50
Activity 5I (CLO2)
Activity Outcome: Program oddNo.java below illustrates the working of a while loop.
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.
51
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:
Activity 5K (CLO2)
Activity outcome: The program LoopDemo.java below illustrates the working of for loop.
52
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:
Reflection:
53
I can understand selection statements. Explain.
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
54
LAB 6: Arrays
Learning Outcomes
This Lab sheet encompasses 4 activities (Activity 6A, 6B, 6C and 6D).
Activity 6A (CLO2)
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:
55
Step 2: Compile and run the program.
Output:
Step 4: Amend the program by adding the following statement before the last statement.
studentArray[0] = new Student();
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 index—a 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.
56
Procedures :
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};
Output:
Activity 6C (CLO2)
57
Procedures:
Step 1: Write the following program and save it as TestArray3.java.
Output:
58
Step 5: Compile and run the program.
Output:
Activity 6D (CLO2)
Procedures:
Step 1: Write the following program and save it as TestArray5.java.
59
Step 2: Compile and run the program.
Output:
Reflection:
________________________________________________________________________________
60
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
61
LAB 7: Classes, Inheritance and Polymorphism
Learning Outcomes
This Lab sheet encompasses 6 activities (Activity 7A until 7F).
Activity 7A (CLO2)
Activity Outcome: Illustrates how to create a method
Procedure:
Step 2: Type the programs given below. Save the program as Act7a.java
62
63
(CLO2)
Activity 7B
Activity Outcome: Illustrates how to create an object for Act6b class and to access it’s method.
Procedure:
Step 1: Type the programs given below
void show()
{
System.out.println(“My Name is “ + name);
System.out.println(“My Age is “ + age);
}
64
(CLO2)
Activity 7C
Activity Outcome: Illustrates how to create a method and call it from main method
Procedure:
class Student
{
void show()
{
System.out.println (“Hi, Good Morning”);
}
}
class Act7c
{
public static void main(String args[])
{
Student obj = new Student();
obj.show();
}
}
65
(CLO2)
Activity 7D
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”);
}
Activity 7E (CLO2)
Activity Outcome: Understand and create constructor.
Procedure:
Step 1: Type the programs given below
class Cons
{
Cons()
{
System.out.println (“I’m automatically called immediately when the
object is created before the new operator completes its job”);
}
}
class Act7e
66
(CLO2)
{
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.
67
(CLO2)
Activity 7F
Activity Outcome: Understand and create constructor overloading.
Procedure:
Step 1: Add the highlighted codes into Activity 7E.
class Cons
{
Cons()
{
System.out.println (“I’m 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!”);
}
}
68
Reflection:
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
69
LAB 8: Classes, Inheritance and Polymorphism
Learning Outcomes
This Lab sheet encompasses 12 activities (Activity 8A until 8L).
Activity 8A (CLO2)
Activity Outcome: Demonstrates the String class constructors.
Procedure:
Step 1: Type the following program.
70
System.out.println(output);
}
}
Activity 8B (CLO2)
Activity Outcome: Demonstrates the length(), charAt() and getChars() method of the String class.
Procedure:
Step 1: Type the following program.
71
72
(CLO2)
Activity 8C
Activity Outcome: Demonstrates the methods equals(), compareTo() of the String class
Procedure:
Step 1: Type the following program.
73
(CLO2)
Activity 8D
Procedure:
Step 1: Type the following program.
74
(CLO2)
Activity 8E
Procedure:
Step 1: Type the following program.
Activity 8F (CLO2)
Procedure:
Step 1: Type the following program.
75
(CLO2)
Activity 8G
Activity Outcome: Demonstrates StringBuffer constructors.
Procedure:
Step 1: Type the following program.
76
(CLO2)
Activity 8H (CLO2)
Activity Outcome: Demonstrates the length() and capacity() methods of the StringBuffer class.
Procedure:
Step 1: Type the following program.
77
Step 2: Compile and execute the above program.
Step 3: Explain the ensureCapacity() and setLength() methods.
Activity 8I (CLO2)
Procedure:
Step 1: Type the following program.
78
Activity 8J (CLO2)
Procedure:
Step 1: Type the following program.
Activity 8K (CLO2)
Procedure:
Step 1: Type the following program.
79
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);
}
}
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.
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.
80
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);
}
}
Procedure:
Reflection:
81
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
__________________________________________________________________________ ______
__________________________________________________________ ______________________
________________________________________________________________________________
____________________________________ ____________________________________________
__________________________________________________________
______________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
__________________________________________________________ ______________________
________________________________________________________________________________
________________________________________________________________________________
82
LAB 9: Classes, Inheritance and Polymorphism
Learning Outcomes
This Lab sheet encompasses 5 activities (Activity 9A, 9B, 9C, 9D and 9E).
Activity 9A (CLO2)
Activity Outcome: Define Super and usage of super keyword in Java Code
Super
83
Activity 9B (CLO2)
Rewrite the program bellow, used super keyword to distinguish between parent class instance variable and
current class instance variable.
3. }
4. class Bike3 extends Vehicle{
7.
System.out.println(speed);
8.
}
9.
public static void main(String args[]){
10.
Bike3 b=new Bike3();
11.12. } b.display();
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. }
84
Activity 9C (CLO2)
Method Overriding
Activity 9D (CLO2)
Activity Outcome: Illustrates Method Overriding in java
Procedure:
85
class Sum
{
int n;
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)
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 A’s rate of interest-10%, Bank’s B rate of interest-9%, Bank’C
rate of interest -7%.
Reflection:
86
I can understand about keyword super in java program. Explain.
________________________________________________________________________________
________________________________________________________________________________
___________________________________________________________ _____________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
87
Activity 10A (CLO2)
Polymorphism
88
BANK
getRateofInterest( ) : int
89
Activity 10C (CLO2)
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
Shape.java
// Constructor
public Shape (String color) {
this.color = color;
}
public String toString() { return
"Shape of color=\"" + color + "\"";
}
90
Reflection:
________________________________________________________________________________
________________________________________________________________________________
___________________________________________________________ _____________________
What I have learnt from all the activities above? (Write in your own word
below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
91
LAB 11: Classes, Inheritance and Polymorphism
Learning Outcomes
This Lab sheet encompasses 6 activities (Activity 11A, 11B, 11C, 11D,11E and 11F).
92
Activity 11A
Abstract Class
(CLO2)
93
State the rules to create abstract class and method
Procedure:
Step 1: Type the following code
Step 2: Save the program
Step 3: Compile and execute the program
Step 4: Write the output
94
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));
}
}
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();
}
}
Procedure :
Bike12.java
95
class Bike12{
abstract
void
}
run()
;
Step 2 : Observe the output.
Output:
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
96
abstract class Shape{ // abstract class
abstract void draw(); // abstract method
}
Output:
Activity Outcome: Demonstrates the implement of polymorphism and interface in Java Program.
Procedure:
Step 1: Type the following program.
interface Person
{
public String getName();
}
class Student implements Person
{
String name="Qistina";
97
public String getName()
{
System.out.println("Student Name:" + name);
return name;
}
}
class Employee implements Person
{
String name="Amirul";
Procedure:
98
Step 1: Type the following program.
interface Animal {
Reflection:
99
I can understand about abstract class in java program. Explain.
________________________________________________________________________________
________________________________________________________________________________
___________________________________________________________ _____________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
__________________________________________________________
______________________
________________________________________________________________________________
________________________________________________________________________________
100
LAB 12: Multithreading and Exception Handling
Learning Outcomes:
This activity encompasses 5 activities. (Activity 12A, 12B, 12C, 12D and 12E)
Procedures:
Step 1: Open Notepad and type the following code:
Step 2: Save, compile and run the program. Save the program as MultithreadingDemo.java.
Observe the output.
101
Activity 12B (CLO2)
Procedures:
Step 1: Open Notepad and type the following code:
Step 2: Save, compile and run the program. Save the program as MultithreadDemo.java. Observe
the output.
Procedures:
Step 1: Open Notepad and type the following code:
102
public void run(){
System.out.println(" This is task one");
}
}
class Thread2 extends Thread{
public void run(){
System.out.println("This is task two");
}
}
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.
Procedures:
Step 1: Open Notepad and type the following code:
103
class ThreadTest extends Thread {
public ThreadTest(String str) {
super(str);
}
}
}
Step 2: Save, compile and run the program. Save the program as Test.java. Observe the output.
104
Reflection:
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
105
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
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:
106
1. Understand concept of exception handling.
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();
}
}
}
ACTIVITY 13B
Procedure :
Step 1: Type the following code
Step 2: Save the program as ArrayExcepDemo.java
107
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:
Activity Outcome : The following example illustrates the concept the concept of ArithmeticException
Procedure :
108
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:
109
ACTIVITY 13D
Procedures :
110
class MultiCatchDemo
{
public static void main(String args[])
{ int
a=10,b=0,c=0; int
arr[]={10,20}; try
{
c=a/b; Output:
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");
} }
}
Procedures :
111
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:
ACTIVITY 13F
Procedures :
112
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:
Reflection:
113
I can understand the concept of exception handling. Explain.
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
What I have learnt from all the activities above? (Write in your own word below)
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
114