Ood - Lab Manual
Ood - Lab Manual
List Of Experiments
3 Matrix Multiplication 7
5 Abstract Class 15
6 Garbage Collector 18
7 File Handling 20
9 String Tokenizer 25
10 Exception Handling 27
11 Multithreading 29
12 Thread Synchronization 33
EXPERIMENT – 1
Program to check whether Palindrome or not
AIM
Write a Java program that checks whether a given string is a palindrome or not.
ALGORITHM
1. SET flag = 1
2. FOR i <- 0 to (length_of_string)/2 , DO
IF X[i] = X[i-1-length_of_string] then
SET flag = 1 and PRINT “Not a palindrome”
3. IF flag = 1
PRINT “String is a palindrome”
CODE
public class Pallindrome1
{
public static void main(String[] args)
{
char x[] = { 'm', 'a', 'l', 'a', 'y', 'a', 'l', 'a', 'm' };
System.out.print("String: ");
for (int i = 0; i < x.length; i++)
System.out.print(x[i]);
boolean flag = true;
for (int i = 0; i < x.length / 2; i++)
{
if (x[i] != x[x.length - i - 1])
{
System.out.print("\nNot a pallindrome");
flag = false;
break;
}
}
if (flag)
System.out.print("\nIt is a pallindrome");
}
}
OUTPUT
String: malayalam
It is a palindrome
EXPERIMENT – 2
Program to find frequency of a given character
AIM
Write a Java Program to find the frequency of a given character in a string.
ALGORITHM
1. SET Counter = 0
3. PRINT Counter
CODE
public class Frequency2
{
public static void main(String args[])
{
char ch = 'a';
char x[] = { 'm', 'a', 'l', 'a', 'y', 'a', 'l', 'a', 'm' };
System.out.print("String: ");
for (int i = 0; i < x.length; i++)
System.out.print(x[i]);
OUTPUT
String: malayalam
Element whose frequency need to be searched: a
Element 'a' has a frequency : 4
EXPERIMENT – 3
Matrix Multiplication
AIM
Write a Java program to multiply two given matrices
ALGORITHM
matrixMultiply(A, B):
Begin
for i in range 0 to r1 - 1, do
for j in range 0 to c2 – 1, do
End for
End for
End for
End
CODE
public class MatrixMultiplication3
{
public static void main(String[] args)
{
int x[][] = { { 6, 2, 7 }, { 4, 3, 2 }, { 7, 2, 9 } };
int y[][] = { { 5, 3, 1 }, { 2, 5, 0 }, { 2, 5, 7 } };
int r1 = x.length, r2 = y.length, c1 = x[0].length, c2 =
y[0].length;
if (r2 == c1)
{
int m[][] = new int[r1][c2];
int i, j, k;
}
} else
System.out.print("\nMatrix multiplication not
possible");
}
}
OUTPUT
Product of two matrix:
48 63 55
30 37 18
57 76 70
EXPERIMENT – 4
Program to implement Inheritance
AIM
Write a Java program which creates a class named 'Employee' having the following members:
Name, Age, Phone number, Address, Salary. It also has a method named 'printSalary( )'
which prints the salary of the Employee. Two classes 'Officer' and 'Manager' inherits the
'Employee' class. The 'Officer' and 'Manager' classes have data members 'specialization' and
'department' respectively. Now, assign name, age, phone number, address and salary to an
officer and a manager by making an object of both of these classes and print the same.
ALGORITHM
1. Create a super class Employee with data members String name, int age, long phone,
String address and float salary.
5. Create 2 subclasses Officer and Manager with data member String specialization and
String department respectively
6. Create a parameterized constructor in both sub classes to get values for data members
and call superclass constructor.
9. Create objects of Officer and Manager in function main() and call print()
CODE
public class lab4
{
public static void main(String args[])
{
Officer obj1 = new Officer("Jack", "221B Baker Street", 22,
9038898420l, 22000.98f, "Data Science");
Manager obj2 = new Manager("Vladamir", "X54 Hendsworth
Street", 56, 7838898420l, 120000, "CSE");
obj1.print();
obj2.print();
}
}
class Employee
{
String name, address;
int age;
long phone;
float salary;
void print()
{
System.out.print("Name:" + name);
System.out.print("\nAddress:" + address);
System.out.print("\nAge:" + age);
System.out.print("\nPhone:" + phone);
}
void printSalary()
{
System.out.print("\nSalary:" + salary + "\n\n");
}
String specialization;
void print()
{
super.print();
System.out.print("\nSpecialization:" + specialization);
printSalary();
}
}
String department;
void print()
{
super.print();
System.out.print("\nDepartment:" + department);
printSalary();
}
OUTPUT
Name:Jack
Address:221B Baker Street
Age:22
Phone:9038898420
Specialization:Data Science
Salary:22000.98
Name:Vladamir
Address:X54 Hendsworth Street
Age:56
Phone:7838898420
Department:CSE
Salary:120000.0
EXPERIMENT – 5
Abstract Class
AIM
Write a java program to create an abstract class named Shape that contains an empty method
named numberOfSides( ). Provide three classes named Rectangle, Triangle and Hexagon
such that each one of the classes extends the class Shape. Each one of the classes contains
only the method numberOfSides( ) that shows the number of sides in the given geometrical
structures.
ALGORITHM
1. Create an abstract class Shape with an abstract function numberOfSides().
2. Create sub classes Rectangle, Triangle and Hexagon that extends Shape class.
3. Create a function numberOfSides() in each class to print number of sides of the
respective geometrical structures
4. Create Main class
5. Create objects of the sub classes in main() function and call numberOfSides()
CODE
public class lab5
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
Hexagon h = new Hexagon();
r.numberOfSides();
t.numberOfSides();
h.numberOfSides();
}
}
AIM
Write a Java program to demonstrate the use of garbage collector
ALGORITHM
1. Create a class Test with data members int a , int b.
3. Override the function finalize () to print address of the object being deleted
CODE
class lab6
{
public static void main(String args[])
{
Test ob1 = new Test(15, 20.3f);
Test ob2 = new Test(343, 32.1f);
Test ob3 = new Test(23, 10.1f);
class Test
{
int a;
float b;
Test(int i, float j)
{
a = i;
b = j;
}
OUTPUT
Garbage Collector called
Object garbage collected : Test@2b3aff6c
Garbage Collector called
Object garbage collected : Test@25fd147b
EXPERIMENT – 7
File Handling
AIM
Write a file handling program in Java with reader/writer.
ALGORITHM
1. Do the following steps inside a try catch block
2. Begin try block
3. Get a line of string from user into a String X using Scanner class object
4. Write X into a file data.txt using FileWriter class object fout
5. Call fout.close()
6. Read contents of file data.txt using FileReader class object fin and display it
7. End try block
8. Handle Exception e in the catch block
CODE
import java.io.*;
import java.util.*;
class lab7
{
public static void main(String args[]) throws IOException
{
try
{
int c;
fin.close();
} catch (Exception e)
{
System.out.println("Error");
}
;
}
}
OUTPUT
Enter data to be entered into the file: Hello World I am MAK
Reading contents from file:
Hello World I am MAK
EXPERIMENT – 8
File Handling Exceptions
AIM
Write a Java program that read from a file and write to file by handling all file related
exceptions.
ALGORITHM
1. Do the following steps inside a try catch block
2. Begin try block
3. Create a FileReader class object fin to open input.txt
4. Create a FileWriter class object fout to open OUTPUT.txt
5. Set c = fin.read()
6. While ( c ! = -1 ),do
7. Invoke fout.write(x) to write the contents to a file.
8. c = fin.read()
9. End while
10. Close the file pointers
11. End try block
12. Handle FileNotFoundException , IOException and general Exception
CODE
import java.io.*;
class lab8
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("Opening input.txt");
FileReader fin = new FileReader("input.txt");
int c;
while ((c = fin.read()) != -1)
{
fout.write((char) c);
}
fin.close();
fout.close();
} catch (FileNotFoundException e)
{
System.out.println("File Not Found");
} catch (IOException e)
{
System.out.println("Input OUTPUT Error");
} catch (Exception e)
{
System.out.println("Error");
}
;
}
}
OUTPUT
Opening input.txt
Copying contents of input.txt to OUTPUT.txt
CONTENT OF “input.txt”:
Hello World
I am MAK
CONTENT OF “OUTPUT.txt”:
Hello World
I am MAK
EXPERIMENT – 9
String Tokenizer
AIM
Write a Java program that reads a line of integers, and then displays each integer, and the sum
of all the integers (Use String Tokenizer class of java.util)
ALGORITHM
1. Read a line containing integers separated by spaces from user
2. Store the content to a variable X using Scanner.
3. Create an object st of StringTokenizer class
4. Set sum = 0
5. While ( st.hasMoreTokens != 0 ) do
6. Read the next token and convert it into Integer and assign it to X
7. Add the value of X to sum
8. End while
9. Print sum
CODE
import java.util.*;
OUTPUT
Enter the numbers separated by spaces:
12345
The numbers are:
12345
Sum: 15
EXPERIMENT – 10
Exception Handling
AIM
Write a Java program that shows the usage of try, catch, throws and finally.
ALGORITHM
1. Define main function of type void and handle IOException
2. Begin try block
3. Read contents of a file data.txt using FileReader object fin
4. Display the file contents
5. Close the file pointer
6. End try block
7. Handle all exceptions using catch block and print “Error” if any exception is caught.
8. Define finally block and print “Program Terminated”
CODE
import java.io.*;
class lab10
{
public static void main(String args[]) throws IOException
{
try
{
int c;
fin.close();
} catch (Exception e)
{
System.out.println("\nError");
} finally
{
System.out.println("\nProgram Terminated");
}
;
}
}
OUTPUT
Reading data from file data.txt :
Hello World I am MAK
Program Terminated
CONTENT OF “input.txt”:
Hello World
I am MAK
EXPERIMENT – 11
Multithreading
AIM
Write a Java program that implements a multi-threaded program which has three threads.
First thread generates a random integer every 1 second. If the value is even, second thread
computes the square of the number and prints. If the value is odd the third thread will print
the value of cube of the number
ALGORITHM
1. Initialise two classes Thread2 and Thread3 extending to Thread class,with a data
member int X and a constructor to give it a value.
2. Define a function run() in Thread2 class to calculate the square of X and print it
3. Create a function run() in Thread3 class to calculate the cube of X and print it
4. Create a class Thread1 and create a function run().
5. Inside run() , create a object rand of Random class.
6. For i=0 to 10 , do
7. Generate a random number within the range of 0 to 9 and store it in a variable x.
8. If x is even ,then
a. Create an object t2 of Thread2 by passing x as argument
b. Call the start function of thread class Thread2
9. Else
a. Create an object t3 of Thread3 by passing x as argument
b. Call the start function of thread class Thread3.
10. End if else
11. Under the try block pause the execution of current thread for 1000ms.
12. Handle InterruptedException
13. End For
14. Create Main class
15. Create a object t1 of Thread1 class in main()
16. Start the thread execution.
CODE
import java.util.Random;
if (x % 2 == 0)
{
t2.start();
} else
{
t3.start();
}
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
System.out.println(e);
}
}
}
}
Thread2(int data)
{
this.x = data;
}
}
class Thread3 extends Thread
{
int x;
Thread3(int data)
{
this.x = data;
}
OUTPUT
Square of 0 is 0
Cube of 1 is 1
Cube of 7 is 343
Cube of 1 is 1
Cube of 1 is 1
Square of 6 is 36
Cube of 5 is 125
Cube of 5 is 125
Cube of 7 is 343
Square of 4 is 16
EXPERIMENT – 12
Thread Synchronization
AIM
Write a Java program that shows thread synchronization.
ALGORITHM
1. Create a class PrintMultiples.
2. Create a synchronized function print() that takes a integer x as parameter
3. Run a loop that prints multiplication table of x upto 5 numbers
4. Create classes Thread1 and Thread2 extending to Thread class
with a data member an object OBJ of PrintMultiples and a constructor to assign it to another
object of PrintMultiples.
5. Create a function run() in Thread1 class and print the first five multiples of five.
6. Create a function run() in Thread2 class and print the first five multiples of two.
7. Create Main class
8. Inside main(), create an object obj of PrintMultiples and two objects of Thread1 and
Thread2 by passing obj
9. Start the execution of thread.
CODE
public class lab12
{
public static void main(String args[])
{
PrintMultiples obj = new PrintMultiples();
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
t1.start();
t2.start();
}
}
class PrintMultiples
{
synchronized void print(int x)
{
for (int i = 1; i <= 5; i++)
System.out.println(x + "*" + i + " =" + x * i);
System.out.println();
}
}
Thread1(PrintMultiples x)
{
this.obj = x;
}
OUTPUT
5*1 =5
5*2 =10
5*3 =15
5*4 =20
5*5 =25
2*1 =2
2*2 =4
2*3 =6
2*4 =8
2*5 =10
EXPERIMENT – 13
Simple Calculator using Java Swing
AIM
Write a Java program that works as a simple calculator. Arrange Buttons for digits and the + -
* % operations properly. Add a text field to display the result. Handle any possible
exceptions like divide by zero. Use Java Swing.
ALGORITHM
1. Create a class Main implementing ActionListener
2. Inside the constructor of main constructor
3. Add a JFrame f and JPanel P to that frame.
4. Set layout as FlowLayout and set frame as visible.
5. Add WindowListener to frame to close the frame.
6. Define required buttons for numbers and operators and a clear button to clear the
field.
7. Add a JTextField to the panel.
8. Set layout of panel to GridLayout
9. Add ActionLstener to the defined buttons.
10. Listen for action performed and assign it to a variable.
11. If number button is pressed then
a. Get the input from text field and concatenate with the current input
b. Display the result in textfield.
12. If an operator is pressed then
a. Get the current input from textfield and convert it to Double and store it in num1.
b. Clear the textfield.
c. Set ‘operator’ variable to the corresponding operator
13. If clear button is pressed, clear the textfield.
14. If the button pressed is "=" then
a. Get the current input from textfield and convert it to Double and store it in num2.
b. Check the operator and do the corresponding operation and store it in result
c. For division operator if num2 = 0 then display Infinite in the textfield.
d. Else, display the result.
15. Create the main() function and call constructor.
CODE
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
lab13()
{
f = new JFrame("Calculator");
p = new JPanel();
f.setLayout(new FlowLayout());
b1 = new JButton("0");
b1.addActionListener(this);
b2 = new JButton("1");
b2.addActionListener(this);
b3 = new JButton("2");
b3.addActionListener(this);
b4 = new JButton("3");
b4.addActionListener(this);
b5 = new JButton("4");
b5.addActionListener(this);
b6 = new JButton("5");
b6.addActionListener(this);
b7 = new JButton("6");
b7.addActionListener(this);
b8 = new JButton("7");
b8.addActionListener(this);
b9 = new JButton("8");
b9.addActionListener(this);
b10 = new JButton("9");
b10.addActionListener(this);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
f.add(p);
f.setSize(350, 420);
f.setVisible(true);
}
// Operations
if (e.getSource() == b11) // +
{
num1 = Double.parseDouble(tf.getText());
tf.setText("");
operator = '+';
}
else if (e.getSource() == b12) // -
{
num1 = Double.parseDouble(tf.getText());
tf.setText("");
operator = '-';
}
else if (e.getSource() == b13) // *
{
num1 = Double.parseDouble(tf.getText());
tf.setText("");
operator = '*';
}
else if (e.getSource() == b14) // /
{
num1 = Double.parseDouble(tf.getText());
tf.setText("");
operator = '/';
}
else if (e.getSource() == b15)// %
{
num1 = Double.parseDouble(tf.getText());
tf.setText("");
operator = '%';
if (operator == '+')
{
result = num1 + num2;
tf.setText(String.valueOf(result));
}
else if (operator == '-')
{
result = num1 - num2;
tf.setText(String.valueOf(result));
}
else if (operator == '*')
{
result = num1 * num2;
tf.setText(String.valueOf(result));
}
if (operator == '/')
{
try
{
if (num2 != 0)
{
result = num1 / num2;
tf.setText(String.valueOf(result));
}
else
{
tf.setText("Infinite");
}
}
catch (Exception i)
{
}
}
if (operator == '%')
{
result = num1 % num2;
tf.setText(String.valueOf(result));
}
}
else if (e.getSource() == b17) // C
{
tf.setText("");
}
else // Numbers
{
temp = tf.getText() + e.getActionCommand();
tf.setText(temp);
}
}
OUTPUT
EXPERIMENT – 14
Traffic Light Simulation using Java Swing
AIM
Write a Java program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and
only one light can be on at a time. No light is on when the program starts
ALGORITHM
1. Create a class Main extending Frame and implementing ItemListener
2. Inside the constructor of Main:-
3. Add CheckBoxes red, yellow, green to the Frame and addItemListeners to it
4. Group the red, yellow, green under the CheckBoxGroup cbg
5. Call repaint()
6. Add WindowListener to Frame to close the window.
7. Set the frame as visible and set the layout to FlowLayout.
8. Add an ItemListener to the checkbox button.
9. Override the function itemStateChanged(ItemEvent e) and call repaint() from it.
10. Override the function paint(Graphics g) and do the following inside the function.
11. Draw 3 ovals of equal dimension separated vertically by an height of 60 using
g.drawOval() function
12. Check if red checkbox is selected. If yes, then set color to red using g.setColor() and
fill the corresponding Oval of red using g.fillOval()
13. Similary check for yellow and green checkboxes and fill the color accordingly
14. Create the main() function and call the constructor.
CODE
import java.awt.*;
import java.awt.event.*;
public class lab14 extends Frame implements ItemListener
{
lab14()
{
cbg = new CheckboxGroup();
red = new Checkbox("Red", cbg, false);
yellow = new Checkbox("Yellow", cbg, false);
green = new Checkbox("Green", cbg, false);
red.addItemListener(this);
yellow.addItemListener(this);
green.addItemListener(this);
add(red);
add(yellow);
add(green);
repaint();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
setSize(300, 300);
setVisible(true);
setLayout(new FlowLayout());
if (cbg.getSelectedCheckbox() == red)
{
g.setColor(Color.red);
g.fillOval(130, 80, 50, 50);
}
else if (cbg.getSelectedCheckbox() == yellow)
{
g.setColor(Color.yellow);
g.fillOval(130, 140, 50, 50);
}
else if (cbg.getSelectedCheckbox() == green)
{
g.setColor(Color.green);
g.fillOval(130, 200, 50, 50);
}
}
OUTPUT
EXPERIMENT – 15
Java Database Connectivity
AIM
Write a Java program to display all records from a table using Java Database Connectivity
(JDBC).
ALGORITHM
1. Create Main class and initialize main function.
2. Create a Connection object con and connect to SQLite database.
3. Create a Statement object st using con.createStatement()
4. Execute queries using st.executeQuery() and store the result in a ResultSet object rs
5. Iterate through the rows of the SQL table using rs.next() and print the columns
according to the data type of column.
6. Close the connection object using con.close()
7. Handle SQLException
CODE
import java.sql.*;
System.out.printf("\
n------------------------------------");
System.out.printf("\n|%-10s |%-10s |%-10s|", "Roll",
"Name", "Marks");
System.out.printf("\
n------------------------------------");
while (rs.next())
System.out.printf("\n|%-10d |%-10s |%-10d|",
rs.getInt(1), rs.getString(2), rs.getInt(3));
System.out.printf("\
n------------------------------------");
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Connected to database.db
Retrieving data from database.db
------------------------------------
|Roll |Name |Marks |
------------------------------------
|1 |Mark |80 |
|2 |Xavier |20 |
|3 |Laden |100 |
------------------------------------