0% found this document useful (0 votes)
60 views

Ood - Lab Manual

The document provides a list of 15 experiments from a lab manual. Each experiment is numbered and includes the experiment name, page number, aim, algorithm, code, and output. The experiments cover topics like checking if a string is a palindrome, finding character frequency in a string, matrix multiplication, inheritance, abstract classes, garbage collection, file handling, exception handling, threading, and Java Swing applications.

Uploaded by

Aswin P T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Ood - Lab Manual

The document provides a list of 15 experiments from a lab manual. Each experiment is numbered and includes the experiment name, page number, aim, algorithm, code, and output. The experiments cover topics like checking if a string is a palindrome, finding character frequency in a string, matrix multiplication, inheritance, abstract classes, garbage collection, file handling, exception handling, threading, and Java Swing applications.

Uploaded by

Aswin P T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

LAB MANUAL

List Of Experiments

Exp No. Experiment Name Page No.


1 Program to check whether a string is palindrome or not 3

2 Program to find frequency of a given character 5

3 Matrix Multiplication 7

4 Program to implement Inheritance 10

5 Abstract Class 15

6 Garbage Collector 18

7 File Handling 20

8 File Handling with Exception 22

9 String Tokenizer 25

10 Exception Handling 27

11 Multithreading 29

12 Thread Synchronization 33

13 Simple Calculator using Java Swing 36

14 Traffic Light Simulation using Java Swing 44

15 Java Database Connectivity 48

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

2. FOR I <- 0 to (length_of_string – 1) , DO

IF (str[i] = given_character) then Increment Counter

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

System.out.print("\nElement whose frequency need to be


searched: " + ch);
int count = 0;
for (int i = 0; i < x.length; i++)
if (x[i] == ch)
count++;
System.out.printf("\nElement '" + ch + "' has a frequency :
" + count);
}
}

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):

Assume dimension of A is (r1 x c1), dimension of B is (r2 x c2)

Begin

   if c1 != r2, then exit

   otherwise define C matrix as (r1 x c2)

   for i in range 0 to r1 - 1, do

      for j in range 0 to c2 – 1, do

         for k in range 0 to c1, do

            C[i, j] = C[i, j] + (A[i, k] * A[k, j])

         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;

System.out.print("Product of two matrix:");


for (i = 0; i < r1; i++)
{
System.out.print("\n");
for (j = 0; j < c2; j++)
{
m[i][j] = 0;
for (k = 0; k < c1; k++)
m[i][j] += x[i][k] * y[k][j];
System.out.print(m[i][j] + " ");
}

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

2. Create a parameterized constructor to get values for the data members

3. Create function print() to print name,age,phone,address.

4. Create function printSalary() to print 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.

7. Create a function print() in sub classes to print specialization and department


respectively and then call print() and printSalary() of super class

8. Create Main class

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

Employee(String a, String b, int c, long d, float e)


{
name = a;
address = b;
age = c;
phone = d;
salary = e;
}

class Officer extends Employee


{

String specialization;

Officer(String a, String b, int c, long d, float e, String s)


{
super(a, b, c, d, e);
specialization = s;

void print()
{
super.print();
System.out.print("\nSpecialization:" + specialization);
printSalary();
}
}

class Manager extends Employee


{

String department;

Manager(String a, String b, int c, long d, float e, String s)


{
super(a, b, c, d, e);
department = s;
}

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

abstract class Shapes


{
abstract void numberOfSides();
}

class Rectangle extends Shapes


{
void numberOfSides()
{
System.out.println("No. of sides in a rectangle: 4");
}
}

class Triangle extends Shapes


{
void numberOfSides()
{
System.out.println("No. of sides in a triangle: 3");
}
}

class Hexagon extends Shapes


{
void numberOfSides()
{
System.out.println("No. of sides in a Hexagon: 6");
}
}
OUTPUT
No. of sides in a rectangle: 4
No. of sides in a triangle: 3
No. of sides in a Hexagon: 6
EXPERIMENT – 6
Garbage Collector

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.

2. Create a parameterized constructor to get values for data members

3. Override the function finalize () to print address of the object being deleted

4. Create Main class

5. Create objects ob1, ob2, ob3 of Test class in main() function

6. Set ob1 = NULL and call garbage collector

7. Set ob1 = ob3 and call garbage collector

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

ob1 = null; // REMOVING MEMORY FOR ob1


System.gc();
ob2 = ob3; // REMOVING MEMORY FOR ob2
System.gc();
}
}

class Test
{
int a;
float b;

Test(int i, float j)
{
a = i;
b = j;
}

public void finalize()


{
System.out.println("Garbage Collector called");
System.out.println("Object garbage collected : " + this);
}
}

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;

Scanner cin = new Scanner(System.in);


System.out.print("\nEnter data to be entered into the
file: ");
String x = cin.nextLine();
cin.close();

FileWriter fout = new FileWriter("data.txt");


fout.write(x);
fout.close();

System.out.print("Reading contents from file:\n");


FileReader fin = new FileReader("data.txt");

while ((c = fin.read()) != -1)


{
System.out.print((char) 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");

FileWriter fout = new FileWriter("OUTPUT.txt");


System.out.println("Copying contents of input.txt to
OUTPUT.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.*;

public class lab9


{
public static void main(String[] args)
{
int sum = 0, x;

Scanner cin = new Scanner(System.in);


System.out.println("Enter the numbers separated by
spaces:");
String str = cin.nextLine();
cin.close();

StringTokenizer st = new StringTokenizer(str);

System.out.println("The numbers are: ");


while (st.hasMoreTokens())
{
x = Integer.parseInt(st.nextToken());
System.out.print(x + " ");
sum += x;
}

System.out.println("\nSum: " + sum);


}

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;

FileReader fin = new FileReader("data.txt");


System.out.println("Reading data from file data.txt :
");
while ((c = fin.read()) != -1)
{
System.out.print((char) 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;

public class lab11


{
public static void main(String args[])
{
Thread1 t1 = new Thread1();
t1.start();
}
}

class Thread1 extends Thread


{

public void run()


{
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
int x = rand.nextInt(10);

Thread2 t2 = new Thread2(x);


Thread3 t3 = new Thread3(x);

if (x % 2 == 0)
{
t2.start();
} else
{
t3.start();
}

try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
System.out.println(e);
}

}
}
}

class Thread2 extends Thread


{
int x;

Thread2(int data)
{
this.x = data;
}

public void run()


{
int y = x * x;
System.out.println("Square of " + x + " is " + y);
}

}
class Thread3 extends Thread
{
int x;

Thread3(int data)
{
this.x = data;
}

public void run()


{
int y = x * x * x;
System.out.println("Cube of " + x + " is " + y);
}

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

class Thread1 extends Thread


{
PrintMultiples obj;

Thread1(PrintMultiples x)
{
this.obj = x;
}

public void run()


{
obj.print(5);
}

class Thread2 extends Thread


{
PrintMultiples obj;
Thread2(PrintMultiples x)
{
this.obj = x;
}

public void run()


{
obj.print(2);
}

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

public class lab13 implements ActionListener


{
char operator;
double num1, num2, result;
String temp;
JFrame f;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13,
b14, b15, b16, b17;
JPanel p;
JTextField tf;

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

b11 = new JButton("+");


b11.addActionListener(this);
b12 = new JButton("-");
b12.addActionListener(this);
b13 = new JButton("*");
b13.addActionListener(this);
b14 = new JButton("/");
b14.addActionListener(this);
b15 = new JButton("%");
b15.addActionListener(this);
b16 = new JButton("=");
b16.addActionListener(this);
b17 = new JButton("C");
b17.addActionListener(this);
tf = new JTextField(11);
tf.setFont(new Font("Times New Roman", Font.BOLD, 33));
f.add(tf);

p.setLayout(new GridLayout(4, 4, 10, 20));


p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(b10);
p.add(b11);
p.add(b12);
p.add(b13);
p.add(b14);
p.add(b15);
p.add(b16);
p.add(b17);
p.setPreferredSize(new Dimension(300, 300));

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
f.add(p);
f.setSize(350, 420);
f.setVisible(true);
}

public void actionPerformed(ActionEvent e)


{

// 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 = '%';

else if (e.getSource() == b16) // =


{
num2 = Double.parseDouble(tf.getText());

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

public static void main(String[] args)


{
new lab13();
}
}

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
{

Checkbox red, yellow, green;


CheckboxGroup cbg;

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

public void itemStateChanged(ItemEvent e)


{
repaint();
}

public void paint(Graphics g)


{

g.drawOval(130, 80, 50, 50);


g.drawOval(130, 140, 50, 50);
g.drawOval(130, 200, 50, 50);

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

public static void main(String[] args)


{
new lab14();
}
}

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

//After compiling Run following command to run the code


//java -classpath ".;sqlite-jdbc-3.34.0.jar" lab15

public class lab15


{
public static void main(String args[])
{
try
{
Connection con =
DriverManager.getConnection("jdbc:sqlite:database.db");
System.out.println("Connected to database.db");

Statement stmt = con.createStatement();

System.out.println("Retrieving data from database.db");


ResultSet rs = stmt.executeQuery("select * from
student");

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

You might also like