Você está na página 1de 78

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/78

FP301 Object Oriented Programming

LAB 1 : Introduction to Java Programming


Hours Learning Outcomes

Duration : 2

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. 2. 3. 4. 5. 6. Identify Java minimum specifications and platform Describe the tools in Java Development Kit (JDK) Identify anatomy of the Java Program. Identify programming style and documentation in java: Identify programming errors in Java: Write a simple Java program.

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/78

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.

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: /** 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!"); } }

3/78

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.

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/78

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/78

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/78

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

7/78

FP301 Object Oriented Programming JVM (can run on multiple platforms) 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. 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

Output:

Activity 1E
Activity Outcome: Identify programming style and documentation in Java program. 8/78

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. class sample2 { public static void main(String args[]) { System.out.println ("Hello Friend"); } }

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). 9/78

FP301 Object Oriented Programming Step 2 : Add any missing statements.

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.

class sample3 ___ ____________ void main(String args[]) ___ System.out.println ("Welcome"); ___ ___

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). Class sample3 { Public static void main(String args[]) 10/78 { System.out.println ("Hello Friend"); } }

FP301 Object Oriented Programming

Step 2 : Save the program in the bin directory, compile and run the program. Step 3 : Observe the output. 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/78

FP301 Object Oriented Programming

Output:

LAB 2 : Fundamental Of Java Programming Learning Outcomes

This Lab sheet encompasses of activities which is 2A, 2B, 2C, 2D, 2E, 2F, 2G, 2H Du and 2I. ration : 2 Hours

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 programs 9. Implements character and Boolean data types, operator precedence in Java programs. 12/78 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.

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:

class DataType { public static void main(String pmas[]) { byte b = 100; // declare variable b as byte, initialized 100 // value to its short s = 3; // declare variable s as short, initialized // 3 value to its int i = 65; // declare variable i as integer, // initialized 65 value to its long l = 123456789; // declare variable l as long, // initialized 123456789 value to its

char

grade = 'A'; // declare variable grade as char, // initialized a to its float basic = 3500; // declare basic as float, initialized // 3500 to its double hra = 525.9; // declare hra as double, initialized // 525.9 to its boolean ispermanent = true; // declare ispermanent as // boolean, initialized true // to its System.out.println(b+","+s+","+i+","+l); System.out.println(basic+","+hra+","+grade+","+ispermanent); } 13/78

FP301 Object Oriented Programming

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

Activity 2B
Activity Outcome: Identify identifies, variables and constants in Java programming. Program CircumferenceOfCircle.java below illustrates variable and constant declarations: 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); } }

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

14/78

FP301 Object Oriented Programming

Activity 2C
Activity Outcome: Implement numeric data types in Java Program.

The following program uses primitive data type of byte and short: class ShortEg { public static void main ( String[] poli ) { byte value = 127; System.out.println("Value = " + value); } }

Procedures:
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output. Step 3 : Change the value of variable values from 127 to 128. Step 4 : Compile and run the program. Observe the output. Output:

Step 5 : Change the value variable values to -129 and try to compile and run the program. What happens? Step 6 : Change the data type to short . Compile and run the program. Is there a difference? Explain. Explanation:

Activity 2D
15/78

FP301 Object Oriented Programming Activity Outcome: Implement numeric data types in Java Program. The following program uses primitive data type of float and double: class DoubleEg { public static void main ( String[] doub ) { float value = 3.4E0.01F; System.out.println("Value = " + value); } }

Procedures:
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output. Output:

Step 2 : Change the value of variable values from 3.4E0.38F to 3.4E0.39F. Step 3 : Compile and run the program. Observe the output. Output : Explanation:

_________________________________________________________________________

Step 4 : Change the data type of variable values to double. Compile and run the program. Is there a difference? Explain. Output : Explanation:

_________________________________________________________________________

Step 6 : Change the value of variable values from 3.4E0.38F to 1.7e308D. 16/78

FP301 Object Oriented Programming

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

Activity 2E
Activity Outcome: Implements character and Boolean data types in Java programs. The following program uses primitive data type of character and boolean : //A program for demonstrating boolean variables public 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); } }

Procedures :
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output. Output:

17/78

FP301 Object Oriented Programming

Activity 2F
Activity Outcome: Implements operator precedence in Java programs. The following program shows the precedence of the operators. 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); } }

Procedures :
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output.

Output:

18/78

FP301 Object Oriented Programming

Activity 2G
Activity Outcome: Implements typecasting in Java programs. The following program shows the implicit and explicit type casting. 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(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" c= " + c); b= " + b); s= " + s); i= " + i); l= " + l); f1= " + f1); f2= " + f2); d2= " + d2); " );

System.out.println(" Types converted" ); short s1 = b; // implicit type casting short s2 = (short) i; //explicit type casting float n1 = (float) i; // from integer change to // floating point int m1 = (int) f1; // from floating point turn to // be integral type System.out.println(" System.out.println(" System.out.println(" System.out.println(" 19/78 } short s1 = short s2 = float n1 = int m1 = " " " " + + s1); + (short)i); + n1); m1);

FP301 Object Oriented Programming

Procedures :
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output. Ouput:

import java.io.*; class IntegerInputSample Activity 2H { public Implements input stream (System.in) and throws IOException Activity Outcome: static void main (String[] args)output stream (System.out) { in in Java programs. InputStreamReader inStream = new InputStreamReader(System.in); how to accepts input data using input The following program InputSample.java show BufferedReader stdin = new stream, convert string value to int and display data using output stream. BufferedReader(inStream); String str; int num; // declare an int variable System.out.println("Enter an integer:"); str = stdin.readLine(); 20/78 num = Integer.parseInt(str); // convert str to int System.out.println("Integer Value: "+num);

} }

FP301 Object Oriented Programming

Procedures :
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output.

Output:

Activity 2I
Activity Outcome: Implements input stream (System.in) and output stream (System.out) in in Java programs. class CommandLineInputSample { The following program Program CommandLineInputSample .java below show how to public static void main(String args[]) accepts input from the command line. { int sum, num1, num2, num3; num1=Integer.parseInt(args[0]); num2=Integer.parseInt(args[1]); num3=Integer.parseInt(args[2]); sum=num1+num2+num3; 21/78 System.out.println("The sum = "+sum); }

FP301 Object Oriented Programming

Procedures :
Step 1 : Type the above program. Step 2 : Compile and run the program. Observe the output.

Output:

LAB 3 : Control Structures in Java Programs


Duration : 2 Hours Learning Outcomes
These 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..else ii. Switch..case 22/78

b. Looping structures:
i. do..while ii. while iii. for

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

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

Output:

Activity 3B
23/78

FP301 Object Oriented Programming

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

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

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. class sample { public static void main (String args[]) { int num; num=Integer.parseInt(args[0]); if (num<0) 24/78 System.out.println("Negative"); else System.out.println("Positive"); } }

FP301 Object Oriented Programming

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

Output:

class highest { public static void main (String args[]) { int x; int y; int z;

Activity 3D

x = Integer.parseInt(args[0]); y = Integer.parseInt(args[1]); z = Integer.parseInt(args[2]);

Activity Outcome : Write program using control structures (if..else nested statement) if(x>y) { The program highest.java below illustrates the use of nested if statements. The program if(x>z) accepts three integers from the user and finds the highest of the three. 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"); 25/78 else System.out.println(z +" is the highest"); } } }

FP301 Object Oriented Programming

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

Output:

26/78

FP301 Object Oriented Programming

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.
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; } } } 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.

Output:

27/78

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: Im Im Im Im Im clever clever clever clever clever

i.

while loops

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

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 its.

ii.

do..while loops

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

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

iii.

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

Procedures:
29/78

FP301 Object Oriented Programming

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

Conclusion:

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

Activity 3G

public program using main(String[] args) { Activity Outcome: Writestatic void looping structures (while, do..while, for statements) int colCount = 0; int rowCount = 0; Programs below illustrates looping structures to print the output: do { ########## colCount = 0; ########## do { ########## System.out.print("#"); colCount++; i. do..while loops } while (colCount < width); System.out.println(); 30/78 rowCount++; } while (rowCount < height); } }

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 its.

ii.

while loops 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++; } 31/78 System.out.println(); rowCount++; }

} }

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 its.

iii.

for loops

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

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

32/78

FP301 Object Oriented Programming

Activity 3H
Activity Outcome : Write program using sentinel value 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 The output would be: Total number of Number of As = Number of Bs = Number of Cs = Number of Ds = Number of Fs = grades = 14 1 4 6 2 1

Procedures:
33/78

FP301 Object Oriented Programming 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.

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 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 System.out.println("Total number of System.out.println("Number of A's = System.out.println("Number of B's = System.out.println("Number of C's = 34/78 System.out.println("Number of D's = System.out.println("Number of E's = } } + gradeD + gradeE; grades : " + allGrade); " + gradeA); " + gradeB); " + gradeC); " + gradeD); " + gradeE);

FP301 Object Oriented Programming

Step 5: Observer the output. Output:

LAB 4 : Arrays
Hours Learning Outcomes

Duration : 2

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. 2. 3. 4. Declare an initialize an array Pass array to methods Return array to methods 35/78 Write program using single and multidimensional array

Hardware/Software: Computer with JDK latest version.

FP301 Object Oriented Programming

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 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 its value.

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] ); }
Compile and run the program. Observe the Output window

} } Step 2:
Step 3:

Output:

36/78

FP301 Object Oriented Programming

Activity 4B
Activity Outcome: Declare and initialize String array. below illustrates the declaration and initialization of the days in a week using verity of loops. .
Program DaysOfTheWeek.java

Procedures :
Step1 : Key-in DaysOfTheWeek.java as below: 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 37/78

FP301 Object Oriented Programming Step 3: Observe the output. Output:

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.

public class Shirt { public int shirtID = 0; // Default ID for the shirt public String description = "-description required-"; // default // The public public public color codes are R=Red, B=Blue, G=Green, U=Unset char colorCode = 'U'; double price = 0.0; // Default price for all shirts 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); 38/78 System.out.println("Shirt price: " + price); System.out.println("Quantity in stock: " + quantityInStock); System.out.println("*****************************"); } // end of display method } // end of class

FP301 Object Oriented Programming

Step 2: Compile the Shirt.java Step 3: Key-in ShirtArrayTest.java as shown below.


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();

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

Step 4: Compile and run the ShirtArrayTest.java Step 5: Observe the output window

39/78

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:
40/78

FP301 Object Oriented Programming Step 1: Key-in DaysOfTheWeek.java as shown below.

/** * 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); Output: } }

Step 2: Compile and run the DaysOfTheWeek.java. Step 3: Observe the output window

41/78

FP301 Object Oriented Programming

Activity 4E
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.

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++ ){ 42/78 ages[i][j] = i * j; System.out.print( ages[i][j] + " " ); } } } }

FP301 Object Oriented Programming

Step 2: Compile and run the JavaTwoDimensionArray.java. Step 3: Observe the output window Output:

LAB 5 : Create classes in Java program. Learning Outcomes


Duration : 2 Hours sheet encompasses of activities which is 5A, 5B and 5C. This Lab By the end of this laboratory session, you should be able to:
5. 6. 7. 8. 9. Create classes in Java Program. Create object in Java program. Create methods in Java program. 43/78 Call methods in Java Programming Pass parameters by value to methods in Java programs.

Hardware/Software: Computer with JDK latest version.

FP301 Object Oriented Programming

Activity 5A
Activity Outcome: Create classes in Java Program. Create methods in Java program. 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.

RECTANGLE - length : double - width : double + setLength()


+ setwidth() + getLength() + getWidth() + getArea() UML graphical notation for classes

UML graphical notation for data fields

UML graphical notation for methods

Kotak: Rectangle Length = 20 Width = 10

44/78

FP301 Object Oriented Programming

new Rectangle() UML graphical notation for object

Procedure:
Step 1: Type below program. 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; }

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)


45/78

FP301 Object Oriented Programming

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()); } } Step 3: Compile RectangleDemo.java. What is the output?

Output:

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/78

FP301 Object Oriented Programming

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

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

Output:

47/78

FP301 Object Oriented Programming

Learning : Object Oriented LAB 6Outcomes This Lab sheet encompasses of activities which are 6A, 6B, 6C and 6D. Programming in JAVA Duration : 2 By the end of this laboratory session, you should be able to: Hours
13. Implement constructor and overloading in Java programs 14. Implement method overloading in Java programs 15. Pass Objects to method 16. Modify the behavior of classes, method, variable, of constructor using modifiers. 48/78

Hardware/Software: Computer with JDK latest version.

FP301 Object Oriented Programming

class Rectangle { int l, b; float p, q; public Rectangle (int x, int y) { l = x; b = y; }

Activity 6A Rectangle public

(int x) { Activity Outcome : Implement constructor and overloading in Java programs l = x; b = x; }

Procedures : Rectangle (float x) public

{ p = a Step 1: Open x;Notepad, as text editor that come with Windows platform. Q = x; } Step 2: Type the below program using text editor. 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()49/78 { return (p * q); }

FP301 Object Oriented Programming

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); Step 3: Save the program as Rectangle.java in bin directory. Rectangle rectangle3 = new Rectangle(2.0f); Step 4: floata areaInThirdConstructor = rectangle3.third(); Open new text editor (Note Pad). System.out.println(The area of a rectangle in third Step 5: Type the below code and save it as ConstructorOverloading.java in bin constructor is : + directory. 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 : + 50/78 areaInFourthConstructor); } }

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. 51/78

FP301 Object Oriented Programming

Step 2: Type the below program using text editor. 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; } }

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.

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); 52/78 System.out.println("Result : " + result); } }

FP301 Object Oriented Programming

Output:

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.

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) 53/78 { System.out.println("[" + location + "] Name: " + firstName + " " + lastName); }

FP301 Object Oriented Programming

Step 3: Save the program as Name.java in bin directory. Step 4: Open a new text editor (Note Pad). Step 5: Type the below code and save it as ChangeName.java in bin directory. 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"); } Step 6: Type the below program in the same file ChangeName.java public static void main(String [] args){ Name myName = new Name("Yahoo", "Mail"); myName.display("Point 1"); changeName1(myName); myName.display("Point 2"); changeName2(myName); 54/78 myName.display("Point 3"); }

FP301 Object Oriented Programming

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. 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


55/78

Duration : 2

FP301 Object Oriented Programming

Hours 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 programs 2. Apply keyword super in Java programs 3. Implement overriding method in Java programs Hardware/Software: Computer with JDK latest version.

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.

package test; public class ClassOne { public void show() { int x,y,result; x=10; 56/78 y=5; result=x*y; System.out.println("The result is "+result); } }

FP301 Object Oriented Programming

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 import test.ClassOne; class PacktestOne { public static void main(String args[]) { ClassOne c1 = new ClassOne(); c1.show(); } } 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 57/78

FP301 Object Oriented Programming

Procedures :
Step 1 : Type below program using text editor (Note Pad). Step 2 : Save your program as SuperClass.java in the bin directory. class SuperClass{ int a; float b; void Show() { System.out.println("b in super class: }

" + b);

Step 3: Open a new text editor (Note Pad). Step 4: Type the below code and save it as SubClass.java in bin directory. 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); Step 5 : Compile and run the program. subobj.Show(); }}

Output: Output:

58/78

FP301 Object Oriented Programming

Activity 7C
Activity Outcome: Implement overriding method in Java programs

Procedures:
Step 1: Type the below program using text editor (Note Pad). Step 2: Save your program as SuperA.java in the bin directory. 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); }

Step 3: Open a new text editor (Note Pad). Step 4: Type the below code and save it as SubClassB.java in bin directory. class SubClassB extends SuperA { int j; SubClassB(int a, int b, int c) { super(a, b); j = a-b-c; } void subtract() 59/78 { super.add(); System.out.println(Total after subtract a, b and c is : " + j); }

FP301 Object Oriented Programming

Step 5: Compile the program. Step 6: Open a new text editor (Note Pad). Step 7: Type the below program and save it as MethodOverriding.java in bin directory. class MethodOverriding { public static void main(String args[]) { SubClass b = new SubClassB(30, 20, 10); b.subtract(); } }

Step 7: Compile and run the program.

Output:

LAB 8 : Object Oriented


60/78

FP301 Object Oriented Programming

JAVA
Hours

Programming in
Duration : 2

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 programs 2. Implement polymorphism in Java programs

Hardware/Software: Computer with JDK latest version.

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. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } } abstract double area(); 61/78

FP301 Object Oriented Programming

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 class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } Step 5: Open a Notepad, type the below program and save it as Triangle.java in the same directory. 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; }

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/78

FP301 Object Oriented Programming

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

Output:

Activity 8B
Activity Outcome : Implement polymorphism in Java program

63/78

FP301 Object Oriented Programming

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. 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; }

64/78

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. 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 { double double return } } calculatePhytagoras() calculate = (dim1 * dim1) + (dim2 * dim2); phytagoras = Math.sqrt(calculate); phytagoras;

65/78

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

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

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

66/78

FP301 Object Oriented Programming

LAB 9 : Object Oriented Programming in JAVA


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

Duration : 2

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


1. 2. 3. 4. Write Java program using String and String Buffer object Convert a String to a primitive data in Java programs Construct program using methods in class string Create a java program using the following classes

Hardware/Software: Computer with JDK latest version.

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/78

FP301 Object Oriented Programming

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 c lass 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); 68/78 }

FP301 Object Oriented Programming

catch(StringIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }

Step 3: Compile and run the program. Step 4: See the result and observe the usage of string buffer.

Output:

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/78

FP301 Object Oriented Programming

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); } } 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/78

FP301 Object Oriented Programming

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

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)

71/78

FP301 Object Oriented Programming

Procedures :
Step 1: Open a new Notepad, type the below code Step 2: Save the Shape { stringBuffer.java in the bin directory interface program as

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


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

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(); } }
Step 4: Run the program and see the output.

72/78

FP301 Object Oriented Programming

LAB 10 : Exception Handling


Duration : 2 Hours 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.

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 import java.lang.* ; Step 2: Type the below program using text editor. 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 ; 73/78 System.out.println("Enter an integer:"); inData = stdin.readLine(); try {

FP301 Object Oriented Programming

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" ); } } Step 3: Save the above program as Square.java in the bin directory 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 :

74/78

FP301 Object Oriented Programming

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

Step 3: Save the above program as ArrayExcepDemo.java in the bin directory Step 4: Compile the program. What the result? OUTPUT :

75/78

FP301 Object Oriented Programming

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

Step 3: Save the above program as Arithemtic.java in the bin directory Step 4: Compile the program. What the result? OUTPUT : 76/78

FP301 Object Oriented Programming

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

Step 3: Save the above program as Arithemtic.java in the bin directory Step 4: Compile the program. What the result? 77/78

FP301 Object Oriented Programming

OUTPUT :

78/78

Você também pode gostar