OOP Lab Manual
OOP Lab Manual
Name _____________________
Roll No ____________________
Semester ____________________
Marks ____________________
Signature ____________________
2018
Object Oriented Programming Lab
Introduction
Object-oriented programming (OOP) is a programming language model organized around
objects rather than "actions" and data rather than logic. Historically, a program has been viewed
as a logical procedure that takes input data, processes it, and produces output data. Object-
oriented programming takes the view that what are really cared about are the objects that is to be
manipulated rather than the logic required to manipulate them.
The first step in OOP is to identify all the objects the programmer wants to manipulate and how
they relate to each other, known as data modeling. Once an object has been identified, it is
generalized as a class of objects which defines the kind of data it contains and any logic
sequences that can manipulate it.
1. Abstraction
2. Encapsulation.
3. Inheritance.
4. Polymorphism.
Java
Java is a programming language and a platform based on object-oriented programming concepts.
It was first released by Sun Microsystems in 1995.
There are lots of applications and websites that will not work unless Java is being installed, and
more are created every day. Java is high level, fast, secure, and reliable.
From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the
Internet, Java is everywhere!
1
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Content
Lab
Lab Objective
No.
1 Introduction to Java
2 Java Programming Elements
3 Java Control Statement & Operators
4 Introducing Classes and Objects
5 Overloading & Access Control
6 Arrays & Strings
7 Inheritance in Java
8 Use of abstract and final
9 Packages & Interfaces
10 Exception Handling
11 Introducing JavaFx – Java GUI
12 Exploring JavaFx
13 JavaFx Application
14 Data Storage and Retrieval using filing in Java
15 Introducing UML Diagram
2
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Lab Details
Lab Marks
Lab Objective Signature
No. Obtained
Introduction to Java
1 Objective: Getting familiar with the Java development kit (JDK). Running
your first Java program using CMD and an IDE.
Student Feedback:
3
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Inheritance in Java
7 Objective: Understanding the concept of inheritance, the superclass and
subclass.
Student Feedback:
Exception Handling
10
Objective: Understand how runtime errors are being handled in Java.
Student Feedback:
Student Feedback:
Exploring JavaFx
12
Objective: Show different JavaFx Layouts and Charts.
Student Feedback:
4
Department of Computer Science - Iqra University
Object Oriented Programming Lab
13 JavaFx Application
Objective: Design a Login page using JavaFx components.
Student Feedback:
Note: Students are advised to write their comments about whether the objective of the lab was achieved in
Student Feedback.
Theory:
5
Department of Computer Science - Iqra University
Object Oriented Programming Lab
What is JDK?
It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like Java
Debugger) to create and compile programs.
JRE is required to run Java programs while JDK is required when you have to do some Java programming.
2. Run the .exe file on your System and follow the steps as given by the installer.
6
Department of Computer Science - Iqra University
Object Oriented Programming Lab
3. Note down the location where j2se has been installed. Java Platform is also called as J2SE (Java 2
Platform Standard Edition)
7
Department of Computer Science - Iqra University
Object Oriented Programming Lab
5. Post installation, you will need to set some environment variables in windows.
6. The path is required to be set for using tools such as javac, java etc.If you are saving the java source
file inside the jdk/bin directory, path is not required to be set because all the tools will be available in
the current directory.But If you are having your java file outside the jdk/bin folder, it is necessary to
set path of JDK.
To set the temporary path of JDK, you need to follow following steps:
For setting the permanent path of JDK, you need to follow these steps:
8
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Go to
MyComputer properties -> advanced tab -> environment variables -> new tab of user variable ->
write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok
9
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Copy the path of the bin folder of the JDK and paste it in the variable value field of the path
variable. So add ";C:\Program Files\Java\jdk1.7.0_02\bin" in the path string.
Note:
The PATH environment variable is a series of directories separated by semicolons (;) and is notcase-
sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.
The new path takes effect in each new command window you open after setting the PATH variable.
10
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Lab Task:
class HelloWorld {
public static void main(String args[]){
System.out.println(“Hello World!!”);
}
}
2. Save it as HelloWorld.java. Naming is strictly case-sensitive; make sure you type as it is given above.
3. Now open a command prompt and change to the directory where you have saved HelloWorld.java
4. Enter SET CLASSPATH.
5. Press enter; this sets the classloader path to search for class files in the current directory.
6. Type the command javac to compile your code. If the compilation is successful, you would not be
shown any errors.
javac HelloWorld.java
Type the command java HelloWorld and press enter. Please note that you did not include any
extension such as .java or .class to the class name you wish to run.
javaHelloWorld
7. You would get nice output greeting “Hello World!!”
What is an IDE?
There are different IDE’s used for Java development including NetBeans and Eclipse.
Before starting to develop the complex programs, you need an IDE. In this workbook we will be using
Eclipse IDE for code writing, compilation and execution.
11
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Download Eclipse form its official website and install it on your system by following the instruction provided
by the installer.
After installation, open eclipse. You will see the welcome screen.
Create new project in eclipse. Click on file menu, select Project, then select Java Project and click
Next. You will see the following screen. Give your project a name and click Finish.
12
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Now right click on your project available in project explorer and create new class.
13
Department of Computer Science - Iqra University
Object Oriented Programming Lab
A window similar to one shown below will appear. Enter the class name and check the checkbox for
public static void main (String[] args). Click finish.
A java file will open with some added code. Just add the following line inside the main()
method.System.out.println("Hello World!!");
14
Department of Computer Science - Iqra University
Object Oriented Programming Lab
The output of this code will be generated in the console window present below.
15
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Lab Assignment:
1. Write a simple java program with command-line argument in java.
16
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Objective:Learning Input/Output handling on Java console. Understanding variables using primitive and non-
primitive data types. Exploring Java’s built in classes.
Theory:
Console input
System.in to the standard input device. Console input is not directly supported in Java, but Scanner class is
used to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();
Console output
Java uses System.out to refer to the standard output device.To perform console output, println method is used
to display a primitive value or a string to the console.
System.out.print("Hello ");
System.out.println("world");
You can use the System.out.printf method to display formatted output on the console.
System.out.printf(“Your Total amount is %4.2f", total);
System.out.printf("count is %d and amount is %f", count, amount);
17
Department of Computer Science - Iqra University
Object Oriented Programming Lab
System.out.println((int)1.7);
The above statement displays 1. When a double value is cast into an int value, the fractional part is
truncated.
Math
Math class file is included for the definitions of math functions listed below. It is written as
java.lang.Math.
Date
Java provides a system-independent
encapsulation of date and time in the
java.util.Date class. The no-arg
constructor of the Date class can be
used to create an instance for the
current date and time.
Lab Task:
18
Department of Computer Science - Iqra University
Object Oriented Programming Lab
1. Write a Java program to take different input from user and store the input in variables with
respective data type and then display the data on the console.
import java.util.Scanner;
}
}
snh=Math.sinh(b);
csh=Math.cosh(b);
19
Department of Computer Science - Iqra University
Object Oriented Programming Lab
tnh=Math.tanh(b);
System.out.println("\nTrignometric Functions");
System.out.println("sin 45 = " + sn);
System.out.println("cos 45 =" + cs);
System.out.println("tan 45 =" + tn);
System.out.println("\nHyperbolic Functions");
System.out.println("sinh 1 = " + snh);
System.out.println("cosh 1 = " + csh);
System.out.println("tanh 1 = " + tnh);
}
}
import java.util.Date;
class DateDemo
{
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 " + msec);
}
}
Lab Assignment:
1. Program the following.
20
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Objective:Understanding the control statements of Java including Loops & if-else.Exploring different
operators used in Java.
Theory:
IterationStatements
A loop can be used to tell a program to execute statements repeatedly.Java provides a powerful construct
called a loop that controls how many times an operation or a sequence of operations is performed in
succession.A loop can be nested inside another loop.Different form of loops can be nested with one another.
1. while loops,
2. do-while loops, and
3. for loops.
Loop Syntax
Selection Statements
Selection Statements of Java programming language decides the next statement for execution.Selection
statements use conditions that are Boolean expressions.A Boolean expression is an expression that evaluates
to a Boolean value: true or false.An if statement can be inside another if statement to form a nested if
statement.
1. If statements
2. If-else statements
3. If-else if
4. Switch
if statement executes the statements if the condition is true. if-else statement is two way statement that
decides which statements to execute based on whether the condition is true or false. Multi-way if-else
statement is the preferred coding style for multiple alternative if statements.
If-else Syntax
21
Department of Computer Science - Iqra University
Object Oriented Programming Lab
if do-while for
if (boolean- if (boolean-expression) if (boolean-expression)
expression) { {
{ //for-the-true-case; // for-1st-case;
statement(s); } }
} else { else if(boolean-expression)
//for-the-false-case; {
} // for-2nd-case;
}
else {
//for-default-case;
}
Switch Syntax
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
casevalueN:
// statement sequence
break;
default:
// default statement sequence
}
Operators in Java
There are many operators provide by Java. Following are the most commonly used operators.
Comparison Operators:
Comparison operators can be used to compare two values. The result of the comparison is a Boolean value:
true or false. Java provides six comparison operators.
22
Department of Computer Science - Iqra University
Object Oriented Programming Lab
LogicalOperators:
The logical can be used to create a compound Boolean expression. Sometimes, whether a statement is
executed is determined by a combination of several conditions.
Lab Task:
1. Write a Java program to use an if-else-if ladder to determine which season a particular month
is in.
23
Department of Computer Science - Iqra University
Object Oriented Programming Lab
..........
// Loops may be nested. .........
class Nested { ........
public static void main(String args[]) { .......
inti, j; ......
for(i=0; i<10; i++) { .....
for(j=i; j<10; j++) ....
System.out.print("."); ...
System.out.println(); ..
} .
}
}
Lab Assignment:
1. Write a program 1 of this lab using switch statement.
2. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are
1, 1. Every subsequent value is the sum of the 2 values preceding it. Write a Java Program that
print the nth value of the Fibonacci sequence?
3. Write a Java program that prompts the user for an integer and then prints out all the prime
numbers up to that Integer?
24
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Theory:
Class
A class consists of
Data(variables)
Methods
Constructors
Lab Task:
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
// ___________ Demo Class ___________
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Adding Constructor
25
Department of Computer Science - Iqra University
Object Oriented Programming Lab
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Lab Assignment:
The class should contain default and parameterized constructor. The constructors should just print
the statement as follows.
“Inside Default Constructor”
“Inside Parameterized Constructor”.
calculateSquare(int x)
calculateCube(int x)
calculateFactorial (int x)
generateTable(int x)
Objective: Understanding concepts method and constructor overloading. Learn how to provide
different access controls on class members
Theory:
Method Overloading
If a class has multiple methods by same name but different parameters, it is known as Method Overloading.
Constructor Overloading
If a class has multiple constructorshaving different parameters, it is known as Constructor Overloading.
Access Control
The access modifiers in java specify accessibility (scope) of a data member, method, constructor or
class.There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
Lab Task:
// Demonstrate method overloading.
classOverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
OverloadDemo(){
System.out.println("No-args constructor ");
}
OverloadDemo(int demo){
System.out.println("Parameterized Constructor :" + demo) ;
}
}
27
Department of Computer Science - Iqra University
Object Oriented Programming Lab
class Overload {
public static void main(String args[])
{
OverloadDemoob = new OverloadDemo();
OverloadDemo ob1 = new OverloadDemo(33);
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Lab Assignment:
1. Design a class named Account that contains:
A private int data field named id for the account (default 0).
A private double data field named balance for the account (default 0).
A private double data field named annualInterestRate that stores the current interest rate (default
0). Assume all accounts have the same interest rate.
A private Date data field named dateCreated that stores the date when the account was created.
A no-arg constructor that creates a default account.
A constructor that creates an account with the specified id and initial balance.
The accessor and mutator methods for id, balance, and annualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate.
A method named getMonthlyInterest() that returns the monthly interest.
A method named withdraws that withdraws a specified amount from the account.
A method named deposit that deposits a specified amount to the account.
Write a test program that creates an Account object with an account ID of 1122, a balance of $20,000,
and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method
to deposit $3,000, and print the balance, the monthly interest, and the date when this account was created.
28
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Theory:
Array
A single array variable can reference a large collection of data. Java and most other high-level
languagesprovide a data structure, the array, which stores a fixed-size sequential collection of elementsof the
same type. Once an array is created, its size is fixed. An array reference variable is used to accessthe elements
in an array using an index
Syntax:
elementType[] arrayRefVar = new elementType[arraySize]; // 1d array
elementType[][] arrayRefVar; // 2d array
Strings
The classes String, StringBuilder, and StringBuffer are used for processing strings. A string is a sequence of
characters. Strings are frequently used in programming. In manylanguages, strings are treated as an array of
characters, but in Java a string is treated as anobject.A String object is immutable; its contents cannot be
changed.
Syntax:
String newString = new String(stringLiteral);
String newString = stringLiteral;
Methods Description
equals(StringLiteral) Returns true if this string is equal to string s1.
equalsIgnoreCase(StringLiteral) Returns true if this string is equal to string s1 case insensitive.
compareTo(StringLiteral) Returns an integer greater than 0, equal to 0, or less than 0 to
indicate whether this string is greater than, equal to, or less than s1
Lab Tasks:
1. Write a program using one-dimensional array of numbers and finds the average of a set of
numbers.
29
Department of Computer Science - Iqra University
Object Oriented Programming Lab
classgetCharsDemo {
public static void main(String args[])
{
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
30
Department of Computer Science - Iqra University
Object Oriented Programming Lab
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Lab Assignment:
1. Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM
is a palindrome?
2. Write a Java program for sorting a given array of numbers in ascending order?
Theory:
31
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of
hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a
set of related items. This class can then be inherited by other, more specific classes, each adding those things
that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that
does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It
inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.
Multilevel Inheritance
You can build hierarchies that contain as many layers of inheritance as you like. As mentioned, it is perfectly
acceptable to use a subclass as a superclass of another. For example, three classes called A, B, and C, C can
be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of
the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass. When an
overridden method is called from within a subclass, it will always refer to the version of that method defined
by the subclass. The version of the method defined by the superclass will be hidden.
There are situations when a superclass is created that only defines a generalized form that will be shared by
all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the
methods that the subclasses must implement.
Lab Task:
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
32
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Multilevel Inheritance
33
Department of Computer Science - Iqra University
Object Oriented Programming Lab
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is " + shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is " + shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Lab Assignment:
1. Design a class named Person and its two subclasses named Student and Employee. Make
Faculty and Staff subclasses of Employee.
A person has a name, address, phone number, and email address. A student has a class status
(freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an
office, salary, and date hired. A faculty member has office hours and a rank. A staff member
34
Department of Computer Science - Iqra University
Object Oriented Programming Lab
has a title. Override the toString method in each class to display the class name and the
person’s name.
Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes
their toString() methods.
Objective: Understand the abstract method & class and final method and class.
Theory:
Abstract Methods
There are cases when we have to create a superclass that only defines a generalized form that will be shared
by all of its subclasses, leaving it to each subclass to fill in the details.
35
Department of Computer Science - Iqra University
Object Oriented Programming Lab
In order to ensure that a subclass does, indeed, override all necessary methods, Java provides abstract
methods. Certain methods can be made mandatory to be overridden by subclasses by specifying the abstract
type modifier.
Abstract Class
Any class that contains one or more abstract methods must also be declared abstract. To declare a class
abstract, abstract keyword is used in front of the class keyword at the beginning of the class declaration.
Final Method
final can be use to prevent overriding. To disallow a method from being overridden, specify final as a
modifier at the start of its declaration. Methods declared as final cannot be overridden.
To declare final method, use this general form:
Final Class
final can be use to prevent inheritance. In order to prevent a class from being inherited, the class is made
final. Declaring a class as final implicitly declares all of its methods as final, too.
To do this, precede the class declaration with final.
Lab Task:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
36
Department of Computer Science - Iqra University
Object Oriented Programming Lab
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Lab Assignment:
1. Consider developing a simple bank application as per given details.
The project contains different classes. One class is Account which is abstract. The Account class
should implement following details;
List of attributes:
protected String id;
protected double balance;
37
Department of Computer Science - Iqra University
Object Oriented Programming Lab
List of methods:
public String getID() // Returns the account id.
public double getBalance() // Returns the current balance.
public abstract boolean withdraw(double amount)
public abstract void deposit(double amount)
Second class is SavingsAccount which extends from Account. The SavingsAccount class should
implement following details;
List of methods:
public void deposit(double amount): // The provided amount is added to the account
public boolean withdraw(double amount):
Implement the withdraw method to take out the provided amount from the account balance.
Incorporate the transaction fee $2 per withdrawal. A withdrawal that potentially lowers the balance
below $10 is not allowed. The balance remains unchanged but the method returns false. If the
withdrawal succeeds, the method returns true.
Theory:
Packages
Packages are containers for classes that are used to keep the class name space compartmentalized. For
example, a package allows you to create a class named List, which you can store in your own package
without concern that it will collide with some other class named List stored elsewhere. Packages are stored in
a hierarchical manner and are explicitly imported into new class definitions.
38
Department of Computer Science - Iqra University
Object Oriented Programming Lab
package pkg;
import pkg1[.pkg2].(classname|*);
Interface
Using interface, you can specify a set of methods that can be implemented by one or more classes. The
interface, itself, does not actually define any implementation. Although they are similar to abstract classes,
interfaces have an additional capability: A class can implement more than one interface. By contrast, a class
can only inherit a single superclass (abstract or otherwise).
Lab Task:
// A simple package
package MyPack;
class Balance {
String name;
doublebal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
} }
classAccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(inti=0; i<3; i++) current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting .class file is also in the MyPack directory. Then, try executing the AccountBalance
class, using the following command line:
javaMyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command.
(Alternatively, you can use one of the other two options described in the preceding section to
specify the path MyPack.)
39
Department of Computer Science - Iqra University
Object Oriented Programming Lab
As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed
by itself. That is, you cannot use this command line:
javaAccountBalance
Interface implementation
interface Callback {
void callback(intparam);
}
Lab Assignement:
1. Write an interface Crawlable with method crawl. Create another interface Moveable with
method move. Then write a class Animal and implement both interfaces to show multiple
inheritance.
Theory:
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception
is a run-time error. In computer languages that do not support exception handling, errors must be checked and
handled manually—typically through the use of error codes, and so on. This approach is as cumbersome as it
is troublesome. Java’s exception handling avoids these problems and, in the process, brings run-time error
management into the object oriented world.
40
Department of Computer Science - Iqra University
Object Oriented Programming Lab
A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a
piece of code. When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it
on. Either way, at some point, the exception is caught and processed.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Lab Task:
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try
block. Immediately following the try block, includes a catch clause that specifies the exception type that you
wish to catch. To illustrate how easily this can be done, the following program includes a try block and a
catch clause that processes the ArithmeticException generated by the division-by-zero error:
class ExceptionHandling {
public static void main(String args[]) {
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero. " + e);
}
finally {
System.out.println("procB's finally");
}
System.out.println("After catch statement.");
}
}
Here is a sample program that creates and throws an exception. The handler that catches the exception
rethrows it to the outer handler.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
41
Department of Computer Science - Iqra University
Object Oriented Programming Lab
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Lab Assignment:
1. Write a program to implement calculator’s basic functionality with an exception handler
that deals with nonnumeric operands; then write another program without using an
exception handler to achieve the same objective. Your program should display a message
that informs the user of the wrong operand type before exiting.
2. Write a program that causes the JVM to throw an OutOfMemoryError and catches and
handles this error.
Objective: Understand the design principles of graphical user interfaces (GUIs) using layout
managers to arrange GUI components. Understand basic component of JavaFx and their
interaction used in different program of Java, such as Label, Button, Text Box, Combo Box
etc.
Theory:
GUI & GUI Components:
A graphical user interface (GUI) presents a user friendly mechanism for interacting with an application. GUIs
42
Department of Computer Science - Iqra University
Object Oriented Programming Lab
are built from GUI components. These are sometimes called controls or widgets. A GUI component is an
object with which the user interacts via mouse, the keyboard, or another form of input.
Introduction to JavaFx
JavaFX has replaced Swing as the recommended GUI toolkit for Java. Furthermore, JavaFX is more
consistent in its design than Swing, and has more features. It is more modern too, enabling you to design GUI
using layout files (XML) and style them with CSS, just like we are used to with web applications. JavaFX
also integrates 2D + 3D graphics, charts, audio, video, and embedded web applications into one coherent GUI
toolkit.
In general, a JavaFX application contains one or more stages which corresponds to windows. Each stage has a
scene attached to it. Each scene can have an object graph of controls, layouts etc. attached to it, called the
scene graph. These concepts are all explained in more detail later. Here is an illustration of the general
structure of a JavaFX application:
Stage: The stage is the outer frame for a JavaFX application. The stage typically corresponds to a window.
Each stage is represented by a Stage object inside a JavaFX application. A JavaFX application has a primary
Stage object which is created for you by the JavaFX runtime.
Scene: To display anything on a stage in a JavaFX application, you need a scene. A stage can only show one
scene at a time, but it is possible to exchange the scene at runtime. A scene is represented by a Scene object
inside a JavaFX application. A JavaFX application must create all Scene objects it needs.
Scene Graph: All visual components (controls, layouts etc.) must be attached to a scene to be displayed, and
that scene must be attached to a stage for the whole scene to be visible. The total object graph of all the
controls, layouts etc. attached to a scene is called the scene graph.
Nodes: All components attached to the scene graph are called nodes. All nodes are subclasses of a JavaFX
class called javafx.scene.Node .
There are two types of nodes: Branch nodes and leaf nodes. A branch node is a node that can contain other
nodes (child nodes). Branch nodes are also referred to as parent nodes because they can contain child nodes.
A leaf node is a node which cannot contain other nodes.
43
Department of Computer Science - Iqra University
Object Oriented Programming Lab
JavaFx Controls
JavaFx controls are JavaFx components which provide some kind of control functionality inside a JavaFx
application. For instance, a button, radio button, table, tree etc.
For a control to be visible it must be attached to the scene graph of some Scene object.
Controls are usually nested inside some JavaFx layout component that manages the layout of controls relative
to each other.
Button
CheckBox
ColorPicker
ComboBox
DatePicker
Label
ListView
Menu
MenuBar
PasswordField
ProgressBar
RadioButton
TableView
TextArea
TextField
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
44
Department of Computer Science - Iqra University
Object Oriented Programming Lab
@Override
public void start(Stage stage) throws Exception {
// Using radiobuttons
radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);
// Using CheckBox
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
//using ComboBOx
Label l2 = new Label("Where do you live: ");
ComboBox comboBox = new ComboBox();
comboBox.getItems().add("Karachi");
comboBox.getItems().add("Lahore");
comboBox.getItems().add("Islamabd");
45
Department of Computer Science - Iqra University
Object Oriented Programming Lab
// uisng ListView
Label edu= new Label("Education");
ObservableList<String> items=
FXCollections.observableArrayList(
"Phd", "Master", "Graduate", "Intermediate",
"Matric");
// adding button
HBox h = new HBox(20);
h.getChildren().addAll(button1, button2);
// adding checkbox
HBox h2 = new HBox(10);
h2.getChildren().addAll(l,c1,c2,c3,c4);
// adding Combobox
HBox h3 = new HBox(10);
h3.getChildren().addAll( l2,comboBox);
//adding date picker
HBox h4 = new HBox(10, l3, datePicker);
//adding listview
HBox h5 = new HBox(10, edu, eduList);
stage.setScene(s);
stage.show();
}
46
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Theory:
JavaFx Layouts
47
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Layouts are the top level container classes that define the UI styles for scene graph objects. In
JavaFX, Layout defines the way in which the components are to be seen on the stage. It basically
organizes the scene-graph nodes. We have several built-in layout panes in JavaFX that are HBox,
VBox, StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is represented by a separate class
which needs to be instantiated in order to implement that particular layout pane.
All these classes belong to javafx.scene.layout package. javafx.scene.layout.Pane class is the base
class for all the built-in layout classes in JavaFX.
Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.
FlowPane Organizes the nodes in the horizontal rows according to the available horizontal
spaces. Wraps the nodes to the next line if the horizontal space is less than the
total width of the nodes
GridPane Organizes the nodes in the form of rows and columns.
HBox Organizes the nodes in a single row.
Pane It is the base class for all the layout classes.
StackPane Organizes nodes in the form of a stack i.e. one onto another
VBox Organizes nodes in a vertical column.
FlowPane
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
48
Department of Computer Science - Iqra University
Object Oriented Programming Lab
BorderPane
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
GridPane
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
49
Department of Computer Science - Iqra University
Object Oriented Programming Lab
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GridPane Experiment");
gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);
JavaFx Charts
In general, a chart is a graphical representation of data. There are various kinds of charts to
represent data such as Bar Chart, Pie Chart, Line Chart, Scatter Chart, etc.
50
Department of Computer Science - Iqra University
Object Oriented Programming Lab
JavaFX Provides support for various Pie Charts and XY Charts. The charts that are represented
on an XY–plane include AreaChart, BarChart, BubbleChart, LineChart, ScatterChart,
StackedAreaChart, StackedBarChart, etc.
Each chart is represented by a class and all these charts belongs to the
package javafx.scene.chart. The class named Chart is the base class of all the charts in JavaFX
and the XYChart is base class of all those charts that are drawn on the XY–plane.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("My First JavaFX App");
pieChart.getData().add(slice1);
pieChart.getData().add(slice2);
pieChart.getData().add(slice3);
primaryStage.setScene(scene);
primaryStage.setHeight(300);
primaryStage.setWidth(1200);
primaryStage.show();
}
51
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Login window:
In the Login.java, we have created two text field, text1 and text2 to set the text for username and password. A
button is created to perform an action. The method text1.getText() get the text of username and the method
52
Department of Computer Science - Iqra University
Object Oriented Programming Lab
text2.getText() get the text of password which the user enters. Then we have create a condition that if the
value of text1 and text2 is admin and password respectively, the user will enter into the next page on clicking
the submit button. The NextPage.java is created to move the user to the next page. In case if the user enters
the invalid username and password, the error message should be displayed.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Reflection;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
53
Department of Computer Science - Iqra University
Object Oriented Programming Lab
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Login Form");
//Adding HBox
HBox hb = new HBox();
hb.setPadding(new Insets(20,20,20,30));
//Adding GridPane
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(20,20,20,20));
gridPane.setHgap(5);
gridPane.setVgap(5);
//DropShadow effect
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetX(5);
dropShadow.setOffsetY(5);
54
Department of Computer Science - Iqra University
Object Oriented Programming Lab
lblMessage.setText("Congratulations!");
lblMessage.setTextFill(Color.GREEN);
}
else{
lblMessage.setText("Incorrect user or
pw.");
lblMessage.setTextFill(Color.RED);
}
txtUserName.setText("");
pf.setText("");
}
});
55
Department of Computer Science - Iqra University
Object Oriented Programming Lab
import java.time.LocalDate;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
Stage window;
Scene scene;
public NextPage() {
addcomponents();
window.setScene(scene);
window.show();
56
Department of Computer Science - Iqra University
Object Oriented Programming Lab
layout.add(edu, 0, 4);
layout.add(eduList, 1, 4);
57
Department of Computer Science - Iqra University
Object Oriented Programming Lab
layout.add(loc, 0, 5);
layout.add(locList, 1, 5);
layout.add(dob, 0, 6);
layout.add(date, 1, 6);
layout.add(btnsignup, 1, 7);
layout.add(btnclear, 1, 7);
layout.setMargin(btnclear, new Insets(0, 0, 0 ,
80));
btnsignup.setOnAction(new
EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Alert alert= new
Alert(AlertType.INFORMATION);
alert.setHeaderText(null);
alert.setContentText("Added
successfully!!");
alert.show();
}
});
Menus
In this section, you will learn about creation of menus, submenus and Separators in JavaFx.
Menu bar contains a collection of menus. Each menu can have multiple menu items these are called
submenu.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
58
Department of Computer Science - Iqra University
Object Oriented Programming Lab
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 300, 250, Color.WHITE);
fileMenu.getItems().addAll(newMenuItem, saveMenuItem,
new SeparatorMenuItem(), exitMenuItem);
sqlMenu.getItems().addAll(mysqlItem, oracleItem,
new SeparatorMenuItem());
59
Department of Computer Science - Iqra University
Object Oriented Programming Lab
sqlMenu.getItems().add(tutorialManeu);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
60
Department of Computer Science - Iqra University
Object Oriented Programming Lab
The File class have several methods for working with directories and files such as creating new directories or
files, deleting and renaming directories or files, listing the contents of a directory etc.
FileReader for text files in your system's default encoding (for example, files containing Western European
characters on a Western European computer).
FileInputStream for binary files and text files that contain 'weird' characters.
package managmentSystem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
String filename="data.txt";
writer.write(record);
writer.newLine();
writer.close();
61
Department of Computer Science - Iqra University
Object Oriented Programming Lab
while((line = buffer.readLine())!=null){
records= line.split(",");
data[i]= records;
i++;
}
return data;
package managmentSystem;
import java.io.IOException;
import java.time.LocalDate;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
62
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Stage window;
Scene scene;
launch(args);
@Override
public void start(Stage primaryStage) throws Exception {
window=primaryStage;
window.setTitle("Signup Screen");
window.setHeight(600);
window.setWidth(400);
window.setResizable(false);
addcomponents();
window.setScene(scene);
window.show();
63
Department of Computer Science - Iqra University
Object Oriented Programming Lab
ObservableList<String> items=
FXCollections.observableArrayList(
"Phd", "Master", "Graduate", "Intermediate",
"Matric");
layout.add(edu, 0, 4);
layout.add(eduList, 1, 4);
layout.add(loc, 0, 5);
layout.add(locList, 1, 5);
layout.add(dob, 0, 6);
layout.add(date, 1, 6);
layout.add(btnsignup, 1, 7);
layout.add(btnclear, 1, 7);
layout.setMargin(btnclear, new Insets(0, 0, 0 , 80));
btnsignup.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
64
Department of Computer Science - Iqra University
Object Oriented Programming Lab
String record="";
String rgender="";
if(rmale.isSelected())
rgender="male";
else
rgender="Female";
record+=rgender+", ";
record+=eduList.getSelectionModel().getSelectedItem()+", ";
record+=locList.getSelectionModel().getSelectedItem()+", ";
record+=date.getValue()+", ";
try {
con.WriteToFile(record);
System.out.println("done");
} catch (IOException e) {
System.out.println("error");
e.printStackTrace();
}
//System.out.println(record);
}
});
65
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Theory
UML
The Unified Modeling Language (UML) is a family of graphical notations, backed by single meta model, that
help in describing and designing software systems, particularly software systems built using the object-oriented
(OO) style.
The UML is a relatively open standard, controlled by the Object Management Group (OMG), an open
consortium of companies. The UML was born out of the unification of the many object-oriented graphical
modeling languages that thrived in the late 1980s and early 1990s.
66
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Class Diagram
A class diagram describes the types of objects in the system and the various kinds of static relationships that
exist among them. Class diagrams also show the properties and operations of a class and the constraints that
apply to the way objects are connected.
The class diagram is not only widely used but also subject to the greatest range of modeling concepts
Representing a Class
67
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Microsoft Visio
Microsoft Visio is a diagramming and vector graphics application and is part of the Microsoft Office family.
The product was first introduced in 1992, made by the Shapeware Corporation. It was acquired by Microsoft in
2000.
Lab Task:
We will use Microsoft Visio in this lab to create class diagram.
68
Department of Computer Science - Iqra University
Object Oriented Programming Lab
69
Department of Computer Science - Iqra University
Object Oriented Programming Lab
Lab Assignment
70
Department of Computer Science - Iqra University
Object Oriented Programming Lab
A client wants you to develop a Hospital Management System as per the details provided below.
There are a lot of people associated with the hospital. Each Person could be associated with
different Hospitals, and a Hospital could employ or serve multiple persons.
Person has derived attributes name and address. Name represents full name and could be
combined from title, given (or first) name, middle name, and family (or last) name.
A Person can be a Patient or Staff. The Staff can be Operations Staff and Administrative Staff.
Doctors and Nurses come under Operations Staff.
Patient can have a unique patient number, date of admission, blood group, sickness, allergies and
prescriptions and a derived attribute age which could be calculated based on her or his birth date.
A Patient can take medicine, give blood test or X-ray, or do exercise as per instructions.
Doctor has some specialty, designation and location of his room. A doctor can examine, provide
prescription and perform surgery/operation of his patient. A Doctor and a nurse can treat many
patients. One patient is treated by 1 or 2 doctors, a senior doctor and a junior doctor.
The hospital consists of wards. Ward is a division of a hospital or a suite of rooms shared by
patients who need a similar kind of care. In a hospital, there are a number of wards, each of which
may be empty or have on it one or more patients. Each ward has a unique name and fixed
capacity. Wards are differentiated by gender of its patients, i.e. male wards and female wards.
71
Department of Computer Science - Iqra University