95
FP301 Object Oriented Programming LAB WORKBOOK CONTENTS LAB 1 : Introduction to JAVA Programming ………………… …… 1 LAB 2 : Fundamental of JAVA Programming ……………………. 11 LAB 3 : Control Structures in JAVA Program ………………...... 21 LAB 4 : Arrays ………………………………….…………………… …34 LAB 5 : Create classes in JAVA Program …………………… …. 42 LAB 6 : Object Oriented Programming in JAVA………………… 47 LAB 7 : Object Oriented Programming in JAVA………………… 54 LAB 8 : Object Oriented Programming in JAVA………………… 59 LAB 9 : Object Oriented Programming in JAVA………………… 65 LAB 10 : Exception Handling ……………………………………….. 71 1/95

Fp301 Lab Print

Embed Size (px)

Citation preview

Page 1: Fp301 Lab Print

FP301 Object Oriented Programming

LAB WORKBOOK CONTENTS

LAB 1 : Introduction to JAVA Programming ………………… …… 1

LAB 2 : Fundamental of JAVA Programming ……………………. 11

LAB 3 : Control Structures in JAVA Program ………………...... 21

LAB 4 : Arrays ………………………………….…………………… …34

LAB 5 : Create classes in JAVA Program …………………… …. 42

LAB 6 : Object Oriented Programming in JAVA………………… 47

LAB 7 : Object Oriented Programming in JAVA………………… 54

LAB 8 : Object Oriented Programming in JAVA………………… 59

LAB 9 : Object Oriented Programming in JAVA………………… 65

LAB 10 : Exception Handling ……………………………………….. 71

1/77

Page 2: Fp301 Lab Print

FP301 Object Oriented Programming

LAB 1 : Introduction to Java Programming

Duration : 2 Hours

Activity 1A

Activity Outcome : Identify Java minimum specifications and platform

To installed Java SE Development Kit on windows platform. Java SE Development Kit can be download from Java web site (http://java.sun.com/javase/6/download.jsp).

Procedures :

Step 1: Installed the Java SE Development Kit 6u 18 for Windows on your computer.

2/77

Learning Outcomes

This Lab sheet encompasses of activities which is 1A, 1B, 1C, 1D, 1E, 1F and 1G.

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

1. Identify Java minimum specifications and platform 2. Describe the tools in Java Development Kit (JDK) 3. Identify anatomy of the Java Program.4. Identify programming style and documentation in java:5. Identify programming errors in Java:6. Write a simple Java program.

Page 3: Fp301 Lab Print

/** The HelloWorldApp class implements an application that simply prints "Hello World!" to standard output. **/

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

{        System.out.println("Hello World!");

}}

FP301 Object Oriented Programming

Step 2: Use Notepad, as text editor that come with Windows platform.

Activity 1B

Activity Outcome : Describe the tools in Java Development Kit (JDK) through application.

1. Create a source file and write source code.

Procedures :

Step 1 : Type the below program using text editor (Note Pad). From the Start menu select Programs > Accessories > Notepad. In a new document, type in the following code:

3/77

Page 4: Fp301 Lab Print

FP301 Object Oriented Programming

Step 2 : Save it as “HelloWorldApp.java”. Place this file in a directory (for example, “c:\java\jdk1.6.0_18\bin\”). Java compliers expect the filename to match the class name. When finished, the dialog box should look like this.

Step 3 : Click Save, and exit Notepad.

2. Compile the source file into a .class file Procedures :

Step 1 : Click run in the Windows Start menu. Type the cmd at the Open mode. Click OK button.

Step 2 : The Command Prompt window should look similar to the following screen.

.

4/77

Page 5: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3 : Change the directory to c:\Program Files\Java\jdk1.6.0_18\bin as screen below:

Step 4 : Compiling your first Java application:

Compilation takes source code (file ending in a .java extension), and converts it into byte-code. This byte-code is low level machine code, which is executed inside a Java Virtual Machine (JVM). Use “javac”

tool to complie Java code. “javac” tool is part of JDK, and must installed in the current path. Compile your first java program using the

following command from DOS prompt. At the prompt, type the following command and press Enter.

javac HelloWorldApp.java

This will produce a Java class file, called HelloWorldApp.class. Once the program is in this form, it ready to run. Check to see that a class file has been created by key- in this command:

5/77

Page 6: Fp301 Lab Print

FP301 Object Oriented Programming

c:\java\jdk1.6.0_18\bin\dir HelloWorpldApp.class

or you receive an error message check for typographical errors in your source code.

Step 5 : Run the program

In the same directory, enter the following command at the prompt:

java HelloWorldApp

The program prints "Hello World!" to the screen. Congratulations! Your program works!

Activity 1C

Activity Outcome : Identify the anatomy of the Java Program.

Analyzing the HelloWorldApp program:

// This is a simple program called “HelloWorldApp.java”The symbol ‘//’ stands for a command line. The compiler ignores a

commented line.

Java also supports multiline comments. These type of comments should begin with a /* and end with a */ or begin with /** and end with */.

6/77

Page 7: Fp301 Lab Print

FP301 Object Oriented Programming

/* This is a comment that Extends to two lines. */

/** This is A multi line comment */

The next line declares a class called HelloWorldApp. To create a class, prefix the keyword class with the classname (which is also the name of the file). class HelloWorldApp

It is always a good practice to begin the class name with a capital letter.

The keyword ‘class’ is used to declare the definition of the class that is begin defined.

‘HelloWorldApp’ is the ‘identifier’ for the name of the class. The entire class definition is done within the open and closed curly braces. This marks the beginning and end of the class definition block.

public static void main (String args[ ])

This is the main method from where the program will begin its execution. All the Java application should have one main method. Let us understand what each word in this statement means.

The ‘public’ keyword is an access modifier. It indicates that the class member can be accessed from anywhere in the program. In this case, the main method is declared as public so that JVM can access this method.

HelloWorldApp.java

Compile javac

HelloworldApp.class (byte code)

Runtime java

JVM (can run on multiple platforms)

7/77

Page 8: Fp301 Lab Print

FP301 Object Oriented Programming

The ‘static’ keyword allows the main to be called without the need to create an instance of the class. But in this case, these is a copy of main method available in memory even if no instance of that class has been created. This is important because the JVM first invokes the main method to execute the program. Hence this method must be static and should not depend on instances of the class begin created.

The ‘void’ keyword tells the complier that the method does not return any value when the method is executed.

Activity 1D Activity Outcome : Identify programming style and documentation in Java.

Write java program with programming style and do documentation.

Procedures :

Step 1 : Type below program using text editor (Note Pad).

Step 2 : Save your program in the “bin” directory.

Step 3 : Compile and run the program.

Output:

Activity 1E

Activity Outcome: Identify programming style and documentation in Java program.

8/77

class sample1 // class name{ // open curly brace the beginning of class block

public static void main(String args[]) // main program // where the program start{ // open curly brace for main block System.out.println ("My Name is Aisyah"); // statement

// to print string} //close curly brace for main block

} // end of class with close curly brace for body of

Page 9: Fp301 Lab Print

FP301 Object Oriented Programming

Write java program with programming style and do documentation.

Procedures :

Step 1 : Type below program using text editor (Note Pad).

Step 2 : Add the appropriate comments and comment style, proper indention and spacing and block styles

Step 3 : Save your program in the “bin” directory.

Step 4 : Compile and run the program.

Rewrite the program above in the text box below :

Activity 1F

Activity Outcome: Identify anatomy and programming style and documentation in Java program.

Write java program with anatomy, programming style and do documentation.

Procedures :

Step 1 : Type below program using text editor (Note Pad).

Step 2 : Add any missing statements.

9/77

class sample2{public static void main(String args[]){System.out.println ("Hello Friend");}}

Page 10: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3 : Add the appropriate comments and comment style, proper indention and spacing and block styles.

Step 4 : Save your program in the “bin” directory.

Step 5 : Compile and run the program.

Rewrite the program above in the text box below :

Activity 1G

Activity Outcome: Identify programming errors in Java.

Identify programming errors in Java, implements programming style and do documention.

Procedures :

Step 1 : Type below program using text editor (Note Pad).

10/77

class sample3___ ____________ void main(String args[]) ___

System.out.println ("Welcome"); ______

Class sample3{

Public static void main(String args[]){ System.out.println ("Hello Friend");

}}

Page 11: Fp301 Lab Print

FP301 Object Oriented Programming

Step 2 : Save the program in the ‘bin’ directory, compile and run the program.

Step 3 : Observe the output.

Step 4: Identify the syntax error in code line 1 and code line 2 and correct any syntax errors.

Step 5 : Add the appropriate comments and comment style, proper indention and spacing and block styles.

Step 6 : Save your program in the “bin” directory.

Step 7 : Compile and run the program again.

Step 8: Rewrite the program above in the text box below :

Output:

11/77

Output:

Page 12: Fp301 Lab Print

FP301 Object Oriented Programming

LAB 2 : Fundamental Of Java Programming

Duration : 2 Hours

12/77

Output:

Learning OutcomesThis Lab sheet encompasses of activities which is 2A, 2B, 2C, 2D, 2E, 2F, 2G, 2H and 2I.

By the end of this laboratory session, students should be able to:7. Identify identifies, variables and constants in Java programming 8. Implements numeric data types in Java programs9. Implements character and Boolean data types, operator precedence in Java

programs.10. Implements typecasting in Java programs.11. Implements input stream(System.in) and output stream (System.out) in Java

programs.

Hardware/Software: Computer with JDK latest version.

Page 13: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 2A

Activity Outcome: Identify identifies, variables and constants in Java programming

Program DataType.java below illustrates the declaration and initialization of variables of byte, short, int and long data type:

13/77

class DataType{ public static void main(String pmas[])

{byte b = 100; // declare variable b as byte, initialized 100

// value to it’s short s = 3; // declare variable s as short, initialized // 3 value to it’s

int i = 65; // declare variable i as integer, // initialized 65 value to it’s

long l = 123456789; // declare variable l as long,// initialized 123456789 value to it’s

char grade = 'A'; // declare variable grade as char, // initialized a to it’s float basic = 3500; // declare basic as float, initialized // 3500 to it’s

double hra = 525.9; // declare hra as double, initialized // 525.9 to it’s

boolean ispermanent = true; // declare ispermanent as // boolean, initialized true

// to it’s System.out.println(b+","+s+","+i+","+l);

System.out.println(basic+","+hra+","+grade+","+ispermanent); }}

Page 14: Fp301 Lab Print

FP301 Object Oriented Programming

Procedure:

Step 1 : Type the above program, compile and execute. What is the output?

Activity 2B

Activity Outcome: Identify identifies, variables and constants in Java programming.

Program CircumferenceOfCircle.java below illustrates variable and constant declarations:

Procedure :

Step 1 : Open Notepad and type the above program, compile and execute. What is the output?

Activity 2C

Activity Outcome: Implement numeric data types in Java Program.

14/77

Output:

Output:

class CircumferenceOfCircle{ public static void main(String ppd[])

{int radius=3; // declare variables radius as int,

// initialized value 3 to radius.final double pi=3.14; // declare constant pi as double,

// initialized value 3.14 to pi.double circumference; // declare circumference as double. circumference=2*pi*3; System.out.println(circumference);

}}

Page 15: Fp301 Lab Print

FP301 Object Oriented Programming

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

Procedures:

Step 1 : Type the above program.

Step 2 : Compile and run the program. 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.

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

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

Activity 2D

Activity Outcome: Implement numeric data types in Java Program.

The following program uses primitive data type of float and double:

15/77

Explanation:

class ShortEg{ public static void main ( String[] poli ) { byte value = 127; System.out.println("Value = " + value); }}

class DoubleEg{ public static void main ( String[] doub ) { float value = 3.4E0.01F; System.out.println("Value = " + value); }}

Output:

Page 16: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures:

Step 1 : Type the above program.

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

Step 2 : Change the value of variable value’s from 3.4E0.38F to 3.4E0.39F.

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

Step 4 : Change the data type of variable value’s to double. Compile and run the program. Is there a difference? Explain.

Step 6 : Change the value of variable value’s from 3.4E0.38F to 1.7e308D.

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

16/77

Output :

Explanation:_________________________________________________________________________

Output :

Explanation:_________________________________________________________________________

Output:

Output:

Page 17: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 2E

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 : Type the above program. Step 2 : Compile and run the program. Observe the output.

Activity 2F

Activity Outcome: Implements operator precedence in Java programs.

The following program shows the precedence of the operators.

17/77

//A program for demonstrating boolean variablespublic class TrueFalse {

public static void main(String [] ags){ char letter;

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

}}

Output:

Page 18: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures :

Step 1 : Type the above program.

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

Activity 2G

18/77

public class precedence { public static void main ( String[] pre ) { System.out.println(6 * 2 / 3); System.out.println(6 / 2 * 3); System.out.println(9 + 12 * (8-3)); System.out.println(9 + 12 * 8 - 3); System.out.println(19 % 3); System.out.println(5 + 19 % 3 - 1); }}

Output:

Page 19: Fp301 Lab Print

FP301 Object Oriented Programming

Activity Outcome: Implements typecasting in Java programs.

The following program shows the implicit and explicit type casting.

Procedures :19/77

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

{System.out.println("Variables created");char c= 'x';byte b= 50;short s = 1996;int i = 32770;long l= 1234567654321L;float f1 = 3.142F;float f2 = 1.2e-5F;double d2 = 0.000000987;

System.out.println(" c= " + c);System.out.println(" b= " + b);System.out.println(" s= " + s);System.out.println(" i= " + i);System.out.println(" l= " + l);System.out.println(" f1= " + f1);System.out.println(" f2= " + f2);System.out.println(" d2= " + d2);System.out.println(" " );

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

short s1 = b; // implicit type castingshort s2 = (short) i; //explicit type castingfloat n1 = (float) i; // from integer change to

// floating pointint m1 = (int) f1; // from floating point turn to

// be integral type

System.out.println(" short s1 = " + s1);System.out.println(" short s2 = " + (short)i);System.out.println(" float n1 = " + n1);System.out.println(" int m1 = " + m1);}

}

Page 20: Fp301 Lab Print

FP301 Object Oriented Programming

Step 1 : Type the above program.

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

Activity 2H

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

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

20/77

Ouput:

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

String str; int num; // declare an int variable

System.out.println("Enter an integer:"); str = stdin.readLine(); num = Integer.parseInt(str); // convert str to int System.out.println("Integer Value: "+num); }}

Page 21: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures :

Step 1 : Type the above program.

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

Activity 2I

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

The following program Program CommandLineInputSample .java below show how to accepts input from the command line.

21/77

Output:

class CommandLineInputSample{

public static void main(String args[]){

int sum, num1, num2, num3;

num1=Integer.parseInt(args[0]);num2=Integer.parseInt(args[1]);num3=Integer.parseInt(args[2]);

sum=num1+num2+num3;System.out.println("The sum = "+sum);

}}

Page 22: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures :

Step 1 : Type the above program.

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

LAB 3 : Control Structures in Java Programs

Duration : 2 Hours

22/77

Output:

Learning OutcomesThese Lab sheet encompasses of activities which is 3A, 3B, 3C, 3D, 3E, 3F and 3G

By the end of this lab, students should be able to:12. Write program using control structures:

a. Selection structures: i. If..elseii. Switch..case

b. Looping structures:i. do..whileii. whileiii. for

Page 23: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 3A

Activity Outcome: Write program using control structures (if statement)

Program InputValue.java below illustrates the execution of a simple if statement. The program checks whether the given number is greater than 100.

Procedure:

Step 1: Type the above program, compile and execute. What is the output?

Activity 3B

Activity Outcome: Write program using control structures (if statement)

Program Marks.java below illustrates the execution of a simple if statement based on two conditions. This program checks whether the marks is between 90 and 100 to print the Grade.

23/77

Output:

class Marks{

public static void main(String args[]){

int marks;marks = Integer.parseInt(args[0]);if ((marks>90) && (marks<100) )

System.out.println("Grade is A");}

}

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

{ int num;

num = Integer.parseInt(args[0]); if(num<100) { System.out.println("Number is less than 100"); } }

}

Page 24: Fp301 Lab Print

FP301 Object Oriented Programming

Procedure:

Step 1: Type the above program, compile and execute. What is the output?

Activity 3C

Activity Outcome: Write program using control structures (if..else statement)

Program sample.java below illustrates the use of the if-else statement. This program accepts a number, checks whether it is less than 0 and displays an appropriate message.

Procedure:

24/77

Output:

class sample{

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

num=Integer.parseInt(args[0]); if (num<0)

System.out.println("Negative"); else

System.out.println("Positive"); }}

Page 25: Fp301 Lab Print

FP301 Object Oriented Programming

Step 1: Type the above program, compile and execute. What is the output?

Activity 3D

Activity Outcome : Write program using control structures (if..else nested statement)

The program highest.java below illustrates the use of nested if statements. The program accepts three integers from the user and finds the highest of the three.

25/77

Output:

class highest{ public static void main (String args[]) { int x; int y; int z; x = Integer.parseInt(args[0]); y = Integer.parseInt(args[1]); z = Integer.parseInt(args[2]);

if(x>y) {

if(x>z)

System.out.println(x + " is the highest");else

System.out.println(z + " is the highest"); } else {

if (y>z) System.out.println(y + " is the highest"); else System.out.println(z +" is the highest");

} }}

Page 26: Fp301 Lab Print

FP301 Object Oriented Programming

Procedure:

Step 1: Type the above program, compile and execute. What is the output?

Activity 3E

Activity Outcome: Write program using control structures (switch..case statement)

Program SwitchDate.java below illustrates switch case execution. In the program, the switch takes an integer value (number of days) as input and displays the appropriate month.

26/77

Output:

import java.io.*;public class SwitchDate{ public static void main(String[] ags) throws Exception { BufferedReader mon = new BufferedReader (new InputStreamReader(System.in));

String m; System.out.print("Enter days [28,30 and 31 days] : "); m = mon.readLine(); byte month = Byte.parseByte(m);

switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println("There are 31 days in that month."); break; case 2: System.out.println("“There are 28 days in that month."); break; case 4: case 6: case 9: case 11: System.out.println("There are 30 days in the month."); break;

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

Page 27: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures:

Step 1: Open a new text file, and then enter the following code to choose a month and display output of days for that month:

Step 2: Save the program as SwithDate.java, and compile and then run the program.

Step 3: Correct errors if any and run the program.

Step 4: Observed the output.

27/77

Output:

Page 28: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 3F

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

Programs below illustrates looping structures to print the output:

Output:

I’m cleverI’m cleverI’m cleverI’m cleverI’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.

ii. do..while loops

28/77

public class WhileTest { public static void main(String[] args) { int i = 0; while (i<5){ System.out.println("I'm clever"); i++; } }}

public class doWhileTest { public static void main(String[] args) { int i = 0; do{ System.out.println("I'm clever"); i++; } while (i<5); }}

Page 29: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures:

Step 1: Open a new text file, and then enter the above code.

Step 2: Observer the output. Try to understand it’s.

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 it’s.

Step 3 : Make a conclusion, for every loop programs that you have observer.

29/77

Conclusion:

public class forTest { public static void main(String[] args) { for (int i=0; i< 5; i++) System.out.println("I'm clever"); } }

Page 30: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 3GActivity Outcome: Write program using looping structures (while, do..while, for statements)

Programs below illustrates looping structures to print the output:

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

i. do..while loops

30/77

public class DoWhileRectangle {

public static int height = 3; public static int width = 10;

public static void main(String[] args) {

int colCount = 0; int rowCount = 0;

do { colCount = 0; do { System.out.print("#"); colCount++; } while (colCount < width);

System.out.println(); rowCount++; } while (rowCount < height); }}

Page 31: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures:

Step 1: Open a new text file, and then enter the above code.

Step 2: Observer the output. Try to understand it’s.

ii. while loops

Procedures:

Step 1: Open a new text file, and then enter the above code.

31/77

public class WhileRectangle { public static int height = 3; public static int width = 10;

public static void main(String[] args) { int colCount = 0; int rowCount = 0;

while (rowCount < height){ colCount = 0; while (colCount < width){ System.out.print("#"); colCount++; } System.out.println(); rowCount++; } }}

Page 32: Fp301 Lab Print

FP301 Object Oriented Programming

Step 2: Observer the output. Try to understand it’s.

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 it’s.

Step 3 : Make a conclusion, what are the comment future for every loop programs that you have observer.

Activity 3H

Activity Outcome : Write program using sentinel value

32/77

Conclusion:

public class ForRectangle { public static int height = 3; public static int width = 10; public static void main(String[] args) { for (int rowCount=0; rowCount<height; rowCount++) { for (int colCount=0; colCount<width; colCount++) System.out.print("#"); System.out.println(); } }}

Write a program to read a list of exam scores (integer percentages in the range 0 to 100) and to output the total number of grades and the number of grades in each letter-grade category (90 to 100 = A, 80 to 89 = B, 70 to 79 = C, 60 to 69 = D, and 0 to 59 = F). The end of the input is indicated by a negative score as a sentinel value. (The negative value is used only to end the loop, so do not use it in the calculations). For example, if the input is

98 87 86 85 85 78 73 72 72 72 70 66 63 50 -1

Page 33: Fp301 Lab Print

FP301 Object Oriented Programming

Procedures:

Step 1: Analyze the input of the problem above. (The loop for sentinel value is negative score).

Step 2: Input the score through keyboard using input stream (BufferedReader or Scanner).

Step 3: Use relational and logical operators to evaluate the score (eg. score >= 90 && score <= 100 will be grade A). Do evaluation for other grades.

Step 4: Program below illustrates the above problem. Open a new text file, and then enter the below code.

33/77

The output would be:

Total number of grades = 14Number of A’s = 1Number of B’s = 4Number of C’s = 6Number of D’s = 2Number of F’s = 1

import java.io.*;class grade {

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

String input; int mark,gradeA=0,gradeB=0,gradeC=0,gradeD=0,gradeE=0;

int allGrade=0; BufferedReader obj1 = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter score (to stop enter -1) : ");

do { input = obj1.readLine();

score = Integer.parseInt(input); if (score >= 90 && score <= 100)

gradeA++; else

if (score >= 80 && score <= 89) ++gradeB;

else

Page 34: Fp301 Lab Print

FP301 Object Oriented Programming

Step 5: Observer the output.

34/77

Output:

if(score >= 70 && score <= 79) ++gradeC;

else if (score >= 60 && score <= 69)

++gradeD; else if (score >= 0 && score <= 59) ++gradeE;

} while (mark != -1); allGrade = gradeA + gradeB + gradeC + gradeD + gradeE; System.out.println("Total number of grades : " + allGrade); System.out.println("Number of A's = " + gradeA); System.out.println("Number of B's = " + gradeB); System.out.println("Number of C's = " + gradeC); System.out.println("Number of D's = " + gradeD); System.out.println("Number of E's = " + gradeE);

}}

Page 35: Fp301 Lab Print

FP301 Object Oriented Programming

LAB 4 : Arrays Duration : 2

Hours

Activity 4A

Activity Outcome: Declare and create arrays of primitive data type

In the java programming language, an array is made up of primitive types, and as with other class types, the declaration does not create the object itself. Instead, the declaration of an

35/77

Learning Outcomes

This Lab sheet encompasses of activities which is 4A, 4B, 4C, 4D and 4E.

By the end of this laboratory session, you should be able to:1. Declare an initialize an array2. Pass array to methods3. Return array to methods4. Write program using single and multidimensional array

Hardware/Software: Computer with JDK latest version.

Page 36: Fp301 Lab Print

FP301 Object Oriented Programming

array creates a reference that can use to refer to an array. The actual memory used by the array elements is allocated dynamically either by a new statement.

Procedures:

Step 1: Key-in JavaArray.java. as shown below.

Program JavaArray.java illustrate declaration an int array and print it’s value.

Step 2: Compile and run the program.

Step 3: Observe the Output window

Activity 4B

Activity Outcome: Declare and initialize String array.

Program DaysOfTheWeek.java below illustrates the declaration and initialization of the days in a week using verity of loops..

Procedures :

Step1 : Key-in DaysOfTheWeek.java as below:

36/77

Output:

public class JavaArray {        /** Creates a new instance of JavaArray */    public JavaArray() {    }        public static void main(String[] args) { // Declare and create int array whose size is 10

//(primitive data type) int[] ages = new int[10]; // or int ages [];                 // Display the value of each entry in the array        for( int i=0; i<ages.length; i++ ){            System.out.print( ages[i] );        }     }    }

Page 37: Fp301 Lab Print

FP301 Object Oriented Programming

public class DaysOfTheWeek {         public static void main(String[] args) {                // Declare and initialize String array of the days of the week        String[] days = {"Sunday","Monday","Tuesday","Wednesday",        "Thursday","Friday","Saturday"};                // Display days of the week using while loop        System.out.println("Display days of week using while loop");        int counter = 0;        while(counter < days.length){            System.out.println(days[counter]);            counter++;        }                // Display days of the week using do-while loop        System.out.println("Display days of week using do-while Loop");        counter = 0;        do{            System.out.println(days[counter]);            counter++;        } while(counter < days.length);                // Display days of the week using for loop        System.out.println("Display days of week using for loop");        for(counter = 0; counter < days.length; counter++){            System.out.println(days[counter]);        }         }    }

Step 2: Build and run the program

Step 3: Observe the output.

37/77

Output:

Page 38: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 4C

Activity Outcome: Declare and create array of class

Program Shirt.java below illustrates the creation of shirt class and create array of shirt.

Procedures:

Step 1: Key-in Shirt.java as shown below.

Step 2: Compile the Shirt.java

38/77

public class Shirt {

public int shirtID = 0; // Default ID for the shirt public String description = "-description required-"; // default // The color codes are R=Red, B=Blue, G=Green, U=Unset public char colorCode = 'U'; public double price = 0.0; // Default price for all shirts public int quantityInStock = 0; // Default quantity for all shirts public Shirt() { }

public Shirt(int ID, String d, char c, double p, int q) { shirtID = ID; description = d; colorCode = c; price = p; quantityInStock = q; }

// This method displays the values for an item public void displayInformation() { System.out.println("******SHIRT INFORMATION******"); System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); System.out.println("Quantity in stock: " + quantityInStock); System.out.println("*****************************");

} // end of display method} // end of class

Page 39: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Key-in ShirtArrayTest.java as shown below.

Step 4: Compile and run the ShirtArrayTest.java

Step 5: Observe the output window

39/77

public class ShirtArrayTest {

public static void main (String args[]) {

Shirt [] shirts; shirts = new Shirt[3];

shirts[0] = new Shirt(44229, "Work", 'G', 29.99, 100); shirts[1] = new Shirt(33429, "Denim", 'R',44.99, 10); shirts[2] = new Shirt(43300, "Mesh", 'B', 79.99, 50);

Shirt firstShirt = shirts[0]; firstShirt.displayInformation();

Shirt secondShirt = shirts[1]; secondShirt.displayInformation();

shirts[2].displayInformation(); } // end main } // end class

Output:

Page 40: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 4D

Activity Outcome: Pass array to methods and return array to methods

Program DaysOfTheWeek.java below illustrates pass array to method and display the name of the days, and the second method is pass array to method, if the index of the the array match, assign the name of the day to another array and return the array to method.

Procedures:

Step 1: Key-in DaysOfTheWeek.java as shown below.

40/77

/** * Author : Azimah Ghazalli * Date : 23/05/2010 * Title : Pass and return aray to method */public class DaysOfTheWeek { // Declare and initialize String array of the days of the week static String[] days = {"Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"}; public static void main(String[] args) { //pass array to methods displayDays(days); //pass array to methods and return array to methods String [] initialDay = displayInitialDays(days); System.out.println("Initial Day " ); for (int i = 0; i<initialDay.length; i++) System.out.println(initialDay[i]); }

// Display days of the week using while loop public static void displayDays(String [] dayName){ int counter = 0; System.out.println("Display days of week using while loop"); while(counter < dayName.length){ System.out.println(dayName[counter]); counter++; } System.out.println(""); }

public static String [] displayInitialDays(String [] dayName){ String [] day = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; for (int i = 1; i < dayName.length; i++) { if (day[i].equals(dayName[i])) day[i]=dayName[i]; } return (day); } }

Page 41: Fp301 Lab Print

FP301 Object Oriented Programming

Step 2: Compile and run the DaysOfTheWeek.java.

Step 3: Observe the output window

Activity 4E

41/77

Output:

Page 42: Fp301 Lab Print

FP301 Object Oriented Programming

Activity Outcome: Write program using multidimensional array.

Program DaysOfTheWeek.java below illustrates pass array to method and display the name of the days, and the second method is pass array to method, if the index of the the array match, assign the name of the day to another array and return the array to method.

Procedures:

Step 1: Key-in JavaTwoDimensionArray.java as shown below.

Step 2: Compile and run the JavaTwoDimensionArray.java.

Step 3: Observe the output window

42/77

public class JavaTwoDimensionArray {        /** Creates a new instance of JavaTwoDimensionArray */    public JavaTwoDimensionArray() {    }           public static void main(String[] args) {

   // Declare and create two dimensional int array whose size is // 10 by 5        int[][] ages = new int[10][5];                // Display the number of rows and columns        System.out.println("ages.length = " + ages.length);        System.out.println("ages[1].length = " + ages[1].length);                // Display the value of each entry in the array        for( int i=0; i<ages.length; i++ ){             System.out.println("\nStarting row " + i);            for( int j=0; j<ages[i].length; j++ ){                ages[i][j] = i * j;                System.out.print( ages[i][j] + " " );            }        }    }  }

Page 43: Fp301 Lab Print

FP301 Object Oriented Programming

LAB 5 : Create classes in Java program.

Duration : 2 Hours

Activity 5A

Activity Outcome: Create classes in Java Program. Create methods in Java program.

43/77

Output:

Learning Outcomes

This Lab sheet encompasses of activities which is 5A, 5B and 5C.

By the end of this laboratory session, you should be able to:5. Create classes in Java Program. 6. Create object in Java program.7. Create methods in Java program.8. Call methods in Java Programming9. Pass parameters by value to methods in Java programs.

Hardware/Software: Computer with JDK latest version.

Page 44: Fp301 Lab Print

FP301 Object Oriented Programming

Program Rectangle.java below illustrates rectangle class program. Rectangle class have several instance methods. The methods are setLength(), setwidth(), getLength(), getWidth() and getArea(). An object name kotak created in main method and use instance variables and rectangle methods. Diagram UML below shows the instance variables, methods and creation of an object for Rectangle class.

UML graphical notation for classes

UML graphical notation for data fields

UML graphical notation for methods

new Rectangle()

UML graphical notation for object

Procedure:

Step 1: Type below program.

44/77

class Rectangle{

private double length;private double width;

public void setLength(double panjang){

length = panjang;}public void setWidth(double lebar){

width = lebar;}public double getLength(){

return length;}public double getWidth(){

return width;}public double getArea(){

return length * width;}

}

Kotak: Rectangle

Length = 20Width = 10

RECTANGLE

- length : double- width : double+ setLength() + setwidth()+ getLength()+ getWidth()+ getArea()

Page 45: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 5B

Activity Outcome: Create object from Rectangle class. Call methods in Java Programming Pass parameters by value to methods in Java programs.

Step 2 : Demonstrate the rectangle methods in another class. (RectangleDemo.java)

Step 3: Compile RectangleDemo.java. What is the output?

45/77

class RectangleDemo{

public static void main(String[]args){

Rectangle kotak = new Rectangle();

kotak.setLength(20.0);kotak.setWidth(10.0);

System.out.println("The box's length: "+kotak.getLength());

System.out.println("The box's width: "+kotak.getWidth());

System.out.println("The box's area: "+kotak.getArea());

}}

Page 46: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 5C

Activity Outcome: Create object from Rectangle class. Call methods in Java Programming Pass parameters by value to methods in Java programs.

Step 1 : Demonstrate the rectangle methods in another class. (RectangleDemo1.java)

46/77

Output:

import java.util.Scanner;class RectangleDemo1{

public static void main(String[]args){

double kotakLength, kotakWidth;

Scanner keyboard = new Scanner(System.in);Rectangle kotak = new Rectangle();

System.out.print("What is the box's length?: ");kotakLength = keyboard.nextDouble();

System.out.print("What is the box's width?: ");kotakWidth = keyboard.nextDouble();

kotak.setLength(kotakLength);kotak.setWidth(kotakWidth);

System.out.println("The box's length: "+kotak.getLength());

System.out.println("The box's width: "+kotak.getWidth());

System.out.println("The box's area: "+kotak.getArea());

}}

Page 47: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Compile RectangleDemo1.java. What is the output?

47/77

Output:

Page 48: Fp301 Lab Print

FP301 Object Oriented Programming

LAB 6 : Object Oriented Programming in JAVA

Duration : 2 Hours

Activity 6A 48/77

Learning Outcomes

This Lab sheet encompasses of activities which are 6A, 6B, 6C and 6D.

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

13. Implement constructor and overloading in Java programs14. Implement method overloading in Java programs15. Pass Objects to method16. Modify the behavior of classes, method, variable, of constructor using modifiers.

Hardware/Software: Computer with JDK latest version.

Page 49: Fp301 Lab Print

FP301 Object Oriented Programming

Activity Outcome : Implement constructor and overloading in Java programs

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform.

Step 2: Type the below program using text editor.

49/77

class Rectangle {

int l, b;float p, q;

public Rectangle (int x, int y) {l = x;b = y;}

public Rectangle (int x){l = x;b = x;}

public Rectangle (float x){p = x;Q = x;}

public Rectangle (float x, float y){p = x;q = y;}

public int first(){return (l * b);}

public int second(){return (l * b);}

public float third(){return (p * q);}

public float fourth(){return (p * q);}

}

Page 50: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the program as Rectangle.java in bin directory.

Step 4: Open a new text editor (Note Pad).

Step 5: Type the below code and save it as ConstructorOverloading.java in “bin” directory.

50/77

public class ConstructorOverloading {

public static void main(String args[]) {

Rectangle rectangle1 = new Rectangle(2,4);int areaInFirstConstructor = rectangle.first();System.out.println(“The area of a rectangle in first

constructor is : “ + areaInFirstConstructor);

Rectangle rectangle2 = new Rectangle(5);int areaInSecondConstructor = rectangle2.second();System.out.println(“The area of a rectangle in second

constructor is : “ + areaInSecondConstructor);

Rectangle rectangle3 = new Rectangle(2.0f);float areaInThirdConstructor = rectangle3.third();System.out.println(“The area of a rectangle in third

constructor is : “ + areaInThirdConstructor);

Rectangle rectangle4 = new Rectangle(3.0f,2.0f);float areaInFourthConstructor = rectangle4.fourth();System.out.println(“The area of a rectangle in fourth

constructor is : “ + areaInFourthConstructor);

}}

Page 51: Fp301 Lab Print

FP301 Object Oriented Programming

Output :

Activity 6B

Activity Outcome : Implement method overloading in Java programs

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform.

Step 2: Type the below program using text editor.

51/77

class Overload {

void test(int a) {System.out.println("a: " + a);}

void test(int a, int b){System.out.println("a and b: " + a + "," + b);}

double test(double a){System.out.println("double a: " + a);return a*a;}

}

Page 52: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the program as Overload.java in bin directory.

Step 4: Open a new text editor (Note Pad).

Step 5: Type the below code and save it as MethodOverloading.java in bin directory.

Output:

52/77

class MethodOverloading {

public static void main(String args[]) {

Overload overload = new Overload();double result;

overload.test(10);overload.test(10, 20);result = overload.test(5.5);

System.out.println("Result : " + result);}

}

Page 53: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 6C

Activity Outcome: Pass Objects to method

Step 1: Open a Notepad, as a text editor that comes with Windows platform.

Step 2: Type the below program using text editor.

Step 3: Save the program as Name.java in bin directory.53/77

class Name{ public String firstName; public String lastName;

public Name() { firstName=""; lastName=""; }

public Name(String first, String last) { firstName = first; lastName = last; }

public void display(String location) { System.out.println("[" + location + "] Name: " +

firstName + " " + lastName); }}

Page 54: Fp301 Lab Print

FP301 Object Oriented Programming

Step 4: Open a new text editor (Note Pad).

Step 5: Type the below code and save it as ChangeName.java in bin directory.

Step 6: Type the below program in the same file ChangeName.java

Activity 6D

Activity Outcome: Modify the behavior of classes, method, variables of constructor using modifiers

Step 1: Open a Notepad, as a text editor that comes with Windows platform.

Step 2: Copy again all the coding in activity 6A in different file.

54/77

public class ChangeNameExample {

public static void changeName1(Name myNameLoc) { myNameLoc.display("Point 1a"); myNameLoc.firstName = "Yahoo"; myNameLoc.lastName = "Answers"; myNameLoc.display("Point 1b"); }

public static void changeName2(Name myNameLoc) { myNameLoc.display("Point 2a"); myNameLoc = new Name("Yahoo","Movies"); myNameLoc.display("Point 2b"); }

public static void main(String [] args){

Name myName = new Name("Yahoo", "Mail"); myName.display("Point 1"); changeName1(myName);

myName.display("Point 2"); changeName2(myName); myName.display("Point 3"); }}

Page 55: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Try to manipulate the whole Rectangle class by change the access modifier for the constructor from public to private, final, abstract or protected. See the result after that. Identify whether the class can use the entire modifier or not.

Step 4: After that, try to change the method first from public modifier and to the private, final and protected. See whether it can run or not. Identify the output that appear on your screen.

LAB 7 : Object Oriented Programming in JAVA

Duration : 2 Hours

55/77

Learning Outcomes

This Lab sheet encompasses of activities which is 7A, 7B and 7C.

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

1. Create packages in Java programs2. Apply keyword super in Java programs3. Implement overriding method in Java programs

Hardware/Software: Computer with JDK latest version.

Page 56: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 7A

Activity Outcome : Create packages in Java programs

Procedures :

Step 1: Create a subdirectory test in the current directory.

Step 2: Type below program using text editor (Note Pad).

Step 3: Save your program as Class1.java in the “test” subdirectory. For example if d:\ is the current directory, then create d:\test and save ClassOne.java in it.

Step 3: Save and compile the program.

Step 3: Open a new text editor (Note Pad).

Step 4: Type the below code and save it as PacktestOne.java in the current directory

56/77

package test;public class ClassOne{ public void show()

{ int x,y,result;

x=10; y=5;

result=x*y;System.out.println("The result is "+result);

}}

import test.ClassOne; class PacktestOne{ public static void main(String args[])

{ClassOne c1 = new ClassOne();c1.show();

}}

Page 57: Fp301 Lab Print

FP301 Object Oriented Programming

Step 5 : If d: is the directory in which the Packtest1.java is present 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.

Step 6: Compile and run the program.

Step 7: Observe the output from the program..

Output:

Activity 7B

Activity Outcome : Apply keyword super in Java programs.

Procedures :

Step 1 : Type below program using text editor (Note Pad).

Step 2 : Save your program as SuperClass.java in the “bin” directory.

57/77

class SuperClass{  

int a;   float b;  

void Show(){ System.out.println("b in super class:  " + b);}

}

Page 58: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Open a new text editor (Note Pad).

Step 4: Type the below code and save it as SubClass.java in bin directory.

Step 5 : Compile and run the program.

Output:Output:

Activity 7C

Activity Outcome: Implement overriding method in Java programs

Procedures:

Step 1: Type the below program using text editor (Note Pad).

58/77

class SubClass extends SuperClass{

int a;    float b;  

SubClass( int p, float q){

     a = p;     super.b = q;   }

   void Show(){

     super.Show();     System.out.println("b in super class:  " + super.b);     System.out.println("a in sub class:    " + a);   }   public static void main(String[] args){

SubClass subobj = new SubClass(1, 5);subobj.Show();}}

Page 59: Fp301 Lab Print

FP301 Object Oriented Programming

Step 2: Save your program as SuperA.java in the “bin” directory.

Step 3: Open a new text editor (Note Pad).

Step 4: Type the below code and save it as SubClassB.java in “bin” directory.

Step 5: Compile the program.

Step 6: Open a new text editor (Note Pad).

59/77

class SuperA {

int i;

SuperA(int a, int b) { i = a-b; }

void subtract(){System.out.println("Total after subtract a and b is : " + i);}

}

class SubClassB extends SuperA {

int j;

SubClassB(int a, int b, int c){

super(a, b); j = a-b-c; }

void subtract(){super.add();System.out.println(”Total after subtract a, b and c is : " + j);}

Page 60: Fp301 Lab Print

FP301 Object Oriented Programming

Step 7: Type the below program and save it as MethodOverriding.java in “bin” directory.

Step 7: Compile and run the program.

Output:

LAB 8 : Object Oriented Programming in JAVA

Duration : 2 Hours

60/77

class MethodOverriding {

public static void main(String args[]) {

SubClass b = new SubClassB(30, 20, 10); b.subtract(); }}

Learning Outcomes

This Lab sheet encompasses of activities which is 8A and 8B.

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

1. Implement abstract classes in Java programs2. Implement polymorphism in Java programs

Hardware/Software: Computer with JDK latest version.

Page 61: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 8A

Activity Outcome : Implement abstract classes in Java program

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform.

Step 2: Type the below program using text editor.

Step 3: Save the above program as Figure.java in “bin” directory

Step 4: Open a new text editor, type the below program and save it as Rectangle.java

61/77

abstract class Figure {

double dim1; double dim2;

Figure(double a, double b){ dim1 = a; dim2 = b; }

abstract double area(); }

class Rectangle extends Figure { Rectangle(double a, double b)

{ super(a, b); } double area()

{ System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } }

Page 62: Fp301 Lab Print

FP301 Object Oriented Programming

Step 5: Open a Notepad, type the below program and save it as Triangle.java in the same directory.

Step 6: Open text editor and type the below program as a main program.

Step 7: Save the program as AbstarctAreas.java

Step 8: Compile and run the program and then see the result.

62/77

class Triangle extends Figure {

Triangle(double a, double b){

super(a, b); } double area()

{ System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } }

class AbstractAreas {

public static void main(String args[]) {

// Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created figref = r;

System.out.println("Area is " + figref.area());

figref = t; System.out.println("Area is " + figref.area()); } }

Page 63: Fp301 Lab Print

FP301 Object Oriented Programming

Output:

Activity 8B

Activity Outcome : Implement polymorphism in Java program

Activity 8B

Activity Outcome: Implement polymorphism in Java programs.

Procedures :

Step 1: Copy all the code in activity 8B in different file

Step 2: Adding another constructor that retrieve both parameter as integer and a method to calculate volume in Rectangle class.

63/77

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b); }

Rectangle(int a, int b){super(a, b);}

double area()

{ System.out.println("Inside Area for Rectangle."); return dim1 * dim2; }}

Page 64: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Do the same thing for the Triangle class. Copy the Triangle class and paste in different file. Create another constructor with retrieve int as for both parameters.

Next, create a method to calculate Pythagoras in Figure class. Use the below formula:

After that create a method to calculate Volume of the rectangle in Figure class

Step 4: Type below code and determine the output.64/77

Page 65: Fp301 Lab Print

FP301 Object Oriented Programming

Step 4: Create a main class to test your program. Rewrite the below code and run it.

65/77

import java.lang.*;public abstract class Figure {

double dim1; double dim2; final int height = 8;

Figure(double a, double b) { dim1 = a; dim2 = b; }

abstract double area();

public double calculateVolumeRectangle() { return dim1 * dim2 * height; }

public double calculatePhytagoras() { double calculate = (dim1 * dim1) + (dim2 * dim2); double phytagoras = Math.sqrt(calculate); return phytagoras; }}

class AbstractAreas {

public static void main(String args[]) {

// Figure f = new Figure(10, 10); // illegal now Figure r = new Rectangle(9, 5); Figure s = new Rectangle(10.5, 15.5);

Figure t = new Triangle(3, 4); Figure u = new Triangle(5.5, 4.5);

System.out.println("Area for Rectangle is: "+r.area()); System.out.println("Area for Rectangle is: "+s.area()); System.out.println("Area for Triangle is: "+t.area()); System.out.println("Area for Triangle is: "+u.area());

System.out.println("The Rectangle have the same are?: "+equalArea(r,s)); System.out.println("The Triangle have the same are?: "+equalArea(t,u));

System.out.println("The Volume for this rectangle is: "+r.calculateVolumeRectangle()); System.out.println("Phytagoras side = "+t.calculatePhytagoras()); } public static boolean equalArea(Figure object1, Figure object2) { return object1.area() == object2.area(); }}

Page 66: Fp301 Lab Print

FP301 Object Oriented Programming

Step 5: Change the access modifier for method calculatePhytagoras from public to private. Try run your program and identify the errors.

LAB 9 : Object Oriented Programming in JAVA

Duration : 2 Hours

66/77

Learning Outcomes

This Lab sheet encompasses of activities which is 9A, 9B, 9C and 9D.

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

1. Write Java program using String and String Buffer object2. Convert a String to a primitive data in Java programs3. Construct program using methods in class string4. Create a java program using the following classes

Hardware/Software: Computer with JDK latest version.

Page 67: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 9A

Activity Outcome : Write Java program using String and String Buffer object

Procedures :

Step 1: Open a new Notepad, type the below code

Step 2: Save the program as stringBuffer.java in the “bin” directory

67/77

import java.io.*;

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

String str;    try

{       System.out.print("Enter your name: ");       str = in.readLine();       str += ", This is the example of SringBuffer class and 's functions.";

       //Create a object of StringBuffer class       StringBuffer strbuf = new StringBuffer();       strbuf.append(str);       System.out.println(strbuf);       strbuf.delete(0,str.length());             //append()       strbuf.append("Hello");       strbuf.append("World");                      System.out.println(strbuf);             //insert()       strbuf.insert(5,"_Java ");                    System.out.println(strbuf);             //reverse()       strbuf.reverse();       System.out.print("Reversed string : ");       System.out.println(strbuf);                    strbuf.reverse();       System.out.println(strbuf);                                //capacity()      System.out.print("Capacity of StringBuffer object : ")

System.out.println(strbuf.capacity());      //print 21      

 //delete() and length()       strbuf.delete(6,strbuf.length());               System.out.println(strbuf);                 }

      

Page 68: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Compile and run the program.

Step 4: See the result and observe the usage of string buffer.

Output:

68/77

                      catch(StringIndexOutOfBoundsException e){

       System.out.println(e.getMessage());     }

}}

Page 69: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 9B

Activity Outcome : Convert a String to a primitive data in Java programs

Procedures :

Step 1: Open a new Notepad, type the below code

69/77

public class StringConvert {

public static void main(String args[]) {

String input = new String("5");

int convert_int = Integer.parseInt(input);System.out.println(“Convert String to Integer ”

+convert_int);

float convert_float = Float.parseFloat(input);System.out.println(“Convert String to Float ”

+convert_float);

double convert_double = Double.parseDouble(input);System.out.println(“Convert String to Double ”

+convert_double);}

}

Page 70: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the program as StringConvert.java

Step 4: Compile and run the program.

Step 5: See the result and the way to convert string into primitive data types.

Activity 9C

Activity Outcome : Construct a program using methods in class string

Procedures :

Step 1: Open a new Notepad, type the below code

Step 2: Type the code and save it as StringTest.java

70/77

public class StringTest {

public static void main(String[] args) {

String message1 = new String("Welcome to JAVA"); String message2 = new String("Welcome to Oracle Site"); //method to calculate length of the string System.out.println("Length of this string is: "+message1.length());

//method to returns the character at the specified index from this string System.out.println("Character at the index 0 from this string is: "+message1.charAt(0));

//method to return the string in UPPERCASE System.out.println("Convert to uppercase: "+message1.toUpperCase()); //method to return the string in LOWERCASE System.out.println("Convert to lowercase: "+message1.toLowerCase());

//method to return a string with blank characters trimmed on both sides System.out.println("After trimmed the string: "+message1.trim());

//method to compare 2 string are equals or not System.out.println("String is not equal: "+message1.equals(message2)); }}

Page 71: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Identify another method in class String. Try to manipulate your input and see the output.

*there are so many methods in String class, please refer to JAVA API to learn another method. Implement the method on your code to see the output.

Activity 9D

Activity Outcome : Create a java Program using the following classes (Interface)

Procedures :

Step 1: Open a new Notepad, type the below code

Step 2: Save the program as stringBuffer.java in the “bin” directory

Step 3: Open a new file, type the below class and save it as Point.java

71/77

interface Shape {

public double area();public double volume();

}

public class Point implements Shape {

static int x, y;public Point() {

x = 0;y = 0;

}public double area() {

return 0;}public double volume() {

return 0;}public static void print() {System.out.println("point: " + x + "," + y);}public static void main(String args[]) {

Point p = new Point();p.print();

}}

Page 72: Fp301 Lab Print

FP301 Object Oriented Programming

Step 4: Run the program and see the output.

LAB 10 : Exception Handling

Duration : 2 Hours

72/77

Learning Outcomes

This Lab sheet encompasses of activities which is 10A, 10B, 10C and 10D.

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

1. Create Java program using Exception Handling

Hardware/Software: Computer with JDK latest version.

Page 73: Fp301 Lab Print

FP301 Object Oriented Programming

Activity 10A

Activity Outcome : Create Java program using Exception Handling (NumberFormat Exception)

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform

Step 2: Type the below program using text editor.

Step 3: Save the above program as Square.java in the “bin” directory

73/77

num = Integer.parseInt( inData ); System.out.println("The square of " + inData + " is " + num*num ); }

catch (NumberFormatException ex ) { System.out.println("You entered bad data." ); System.out.println("Run the program again." ); } System.out.println("Good-by" ); }}

import java.lang.* ;import java.io.* ;public class Square { public static void main ( String[] a ) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(

System.in ) ); String inData; int num ;

System.out.println("Enter an integer:"); inData = stdin.readLine(); try {

Page 74: Fp301 Lab Print

FP301 Object Oriented Programming

Step 4: Compile the program. Then run the program and key in the value 123. What the result?

OUTPUT :

Step 5: Compile the program again and then run the program by entered the value JAVA WORLD. What the result?

OUTPUT :

Activity 10B

Activity Outcome : Create Java program using Exception Handling (ArrayIndexOutOfBounds Exception)

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform

Step 2: Type the below program using text editor.

74/77

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"); }

}}

Page 75: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the above program as ArrayExcepDemo.java in the “bin” directory

Step 4: Compile the program. What the result?

OUTPUT :

Activity 10C

Activity Outcome : Create Java program using Exception Handling (Arithmethic Exception)

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform

Step 2: Type the below program using text editor.

75/77

class Arithmetic{

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 e){

System.out.println("Caught Exception :- " + e.getMessage()); }

System.out.println("The Value of C:- " + C);}

}

Page 76: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the above program as Arithemtic.java in the “bin” directory

Step 4: Compile the program. What the result?

OUTPUT :

Activity 10D

Activity Outcome : Create Java program using Exception Handling (Use Finally keyword)

Procedures :

Step 1: Open a Notepad, as text editor that come with Windows platform

Step 2: Type the below program using text editor.

76/77

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");} }

}

Page 77: Fp301 Lab Print

FP301 Object Oriented Programming

Step 3: Save the above program as Arithemtic.java in the “bin” directory

Step 4: Compile the program. What the result?

OUTPUT :

77/77