0% found this document useful (0 votes)
5 views82 pages

1 Oops Lab Manual Soundarya Senthil Murugan 2024

Uploaded by

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

1 Oops Lab Manual Soundarya Senthil Murugan 2024

Uploaded by

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

EX.

NO:1 Develop a Java Program for understanding reference to an instance of a


class (object), methods

AIM

To develop a Java application to generate Electricity bill with the following members:
Consumer no., consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial). Compute the bill amount using the following tariff.

If the type of the EB connection is domestic, calculate the amount to be paid as follows:

o First 100 units - Rs. 1 per unit


o 101-200 units - Rs. 2.50 per unit
o 201 -500 units - Rs. 4 per unit
o 501 units - Rs. 6 per unit

If the type of the EB connection is commercial, calculate the amount to be paid as follows:

o First 100 units - Rs. 2 per unit


o 101-200 units - Rs. 4.50 per unit
o 201 -500 units - Rs. 6 per unit
o 501 units - Rs. 7 per unit

PROCEDURE

1. Start
2. Create a class Ebill with three member functions: getdata(), calc() and
display() and object ob is created for another class Ebconsumer.
3. Create another class Ebconsumer which defines the above methods.
4. Using getdata() function get the consumed units for current and previous month .
5. Using calc()function calculate the amount depending on the type of EB
connection and no. of units consumed.
6. Using display() function display the bill.
7. Stop.

1
PROGRAM

import java.util.*;
class Ebill
{
public static void main (String args[])
{
Ebconsumer ob = new Ebconsumer();
ob.getdata();
ob.calc();
ob.display();
}
}
class Ebconsumer
{
String consumer_name,consumer_type;
long ebill_no;
double current_reading,previous_reading,total_bill,units;
Scanner in = new Scanner(System.in);
void getdata()
{
System.out.println("Enter Type of connection (D for Domestic or C for Commercial): ");
consumer_type=in.next();
System.out.println("Enter consumer number:");
ebill_no=in.nextLong();
System.out.println("Enter consumer name:");
consumer_name=in.next();
System.out.println("Enter previous month reading:");
previous_reading= in.nextDouble();
System.out.println("Enter current month reading:");
current_reading= in.nextDouble();
}

2
void calc()
{
if(previous_reading<current_reading)
{
units=current_reading - previous_reading;
if(consumer_type.equals("D"))
{
if (units<=100)
total_bill=units*1;

else if (units<=200)
total_bill=(100*1+(units-100)*2.50);

else if(units<=500)
total_bill=(100*1+100*2.50)+(units-200)*4;
else
total_bill= (100*1+100*2.50+300*4+(units-500)*6);
}
else
{
if (units<=100)
total_bill=units*2;

else if (units<=200)
total_bill=(100*2+(units-100)*4.50);

else if(units<=500)
total_bill=(100*2+100*4.50)+(units-200)*6;
else
total_bill= (100*2+100*4.50+300*6+(units-500)*7);
}
}}

3
void display()
{
System.out.println("************ELECTRICITY BILL************");
System.out.println("Consumer number = "+ebill_no);
System.out.println("Consumer name = "+consumer_name);

if(consumer_type.equals("D"))
System.out.println("Type of connection = DOMESTIC ");
else
System.out.println("Type of connection = COMMERCIAL ");

System.out.println("Current Month Reading = "+current_reading);


System.out.println("Previous Month Reading = "+previous_reading);
System.out.println("Total units = "+units);
System.out.println("Total bill = RS "+total_bill);
}
}

4
OUTPUT

RESULT

Thus the java program to generate electricity bill was implemented and executed successfully.

5
EX. NO:2 Develop a Program to implement Constructor Overloading.

AIM

To perform Overloading of Constructor in java

PROCEDURE

1. Start

2. Create a class Student with instance variables id and name.

3. Create a default constructor as same name that of class name.

4. Create parameterized constructor which initializes the instance variables.

5. Create object for Student class and perform constructor overloading.

6. Print the default and parameterized constructor initialized values.

7. Stop.

6
PROGRAM

package constructoroverloading;

public class Constructoroverloading


{
int id;
String name;
Constructoroverloading()
{
System.out.println("this a default constructor");
}
Constructoroverloading(int i, String n)
{
id = i;
name = n;
}
public static void main(String[] args)
{
Constructoroverloading s1 = new Constructoroverloading();
Constructoroverloading s2 = new Constructoroverloading(10, "David");

System.out.println("\nDefault Constructor values: \n");


System.out.println("Student Id : "+s1.id + "\nStudent Name : "+s1.name);

System.out.println("\nParameterized Constructor values: \n");


System.out.println("Student Id : "+s2.id + "\nStudent Name : "+s2.name);

7
OUTPUT

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

RESULT

Thus the java program to perform Constructor overloading was implemented and executed successfully.

8
EX. NO:3 Develop a Java Program to implement String Handling Methods

AIM

To perform String operations in java using String Handling Methods

PROCEDURE

1. Start

2. Declare two strings s1 and s2 and initialize.

3. Perform String operations such as

a) String Concatenation
b) Finding char in a string using index position
c) Comparing 2 string methods
d) Comparing 2 strings ignoring case.
e) Finding the hash code of a string
f) Finding index position for a given character
g) Finding last index position for a given character
h) Finding the length of a string
i) Replacing one character with another character in a given string
j) Finding the substring in a given string
k) Converting the given string to lower case
l) Converting the given string to upper string
m) Trimming the spaces in a given string

4. Stop.

9
PROGRAM

public class StrMethods {

public static void main(String[] args) {

String s1="VTHTCSE";

String s2="CSE department";

System.out.println("the concatenation of two strings is "+s1.concat(s2));

System.out.println("the character at 7th place of string 2 is "+s2.charAt(7));

System.out.println("the comparison of two strings is "+s1.compareTo(s2));

System.out.println("Boolean comparison ignoring case "+s1.equalsIgnoreCase(s2));

System.out.println("hash code of string 2 is "+s2.hashCode());

System.out.println("index of E in string 2 is "+s2.indexOf('e',3));

System.out.println("index of E in string 2 from last is "+s2.lastIndexOf('e',16));

System.out.println("length of string 2 is "+s2.length());

System.out.println("after replacing e with k in string 1, string 1 = "+s1.replace('E','K'));

System.out.println("substring of string 2 = "+s2.substring(4));

System.out.println("substring of string 2 from 4 to 9"+s2.substring(4,9));

System.out.println("lower case of string1 is ="+s1.toLowerCase());

System.out.println("UPPER case of string 2 = "+s2.toUpperCase());

System.out.println("after trimming, string 2 ="+s2.trim());

10
OUTPUT

the concatenation of two strings is VTHTCSECSE department

the character at 7th place of string 2 is a

the comparison of two strings is 19

Boolean comparison ignoring case considerations false

hash code of string 2 is 1401753213

index of E in string 2 is 5

index of E in string 2 from last is 11

length of string 2 is 14

after replacing e with k in string 1, string 1 = VTHTCSK

substring of string 2 = department

substring of string 2 from 4 to 9depar

lower case of string1 is =vthtcse

UPPER case of string 2 = CSE DEPARTMENT

after trimming, string 2 =CSE department

RESULT

Thus the java program to perform string operations using string handling methods has been implemented
and executed successfully.

11
EX. NO:4a Implementation of Inheritance using Java.

AIM

To implement Single Inheritance in java

PROCEDURE

1. Start
2. Create a Class Named As C1 With Two Variable l & b.
3. Extends the Class C1 in New Class C2 And Create a Constructor c2(int,int).
4. In c2(int,int) Constructor Multiply the Values.
5. In Main Method Read Two Values And Pass The Values to c2(l,b).
6. Display the Result.
7. Stop.

12
PROGRAM

import java.io.*;

class c1 {

int l,b; }

class c2 extends c1 {

c2(int x, int y)

l=x;

b=y;

System.out.println("\n The Volume is : "+ (l*b));

}}

class inhr

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

int len,brth;

InputStreamReader r = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(r);

System.out.print("\n Enter the Value of Length : ");

len=Integer.parseInt(br.readLine());

System.out.print("\n Enter the Value of Berth : ");

brth=Integer.parseInt(br.readLine());

c2 c=new c2(len,brth); }}

13
OUTPUT

D: \Java>javac inhr.java

D:\Java>java inhr

Enter the Value of Length : 20

Enter the Value of Berth : 35

The Volume is : 700

RESULT

Thus the Above Simple Inheritance Program has been implemented and executed successfully.

14
EX. NO:4b Implementation of Inheritance using Java.

AIM

To implement Multilevel Inheritance in java

PROCEDURE

1. Start
2. Create a Class Named As ‘a’ With ipo() Method And Get the Value.
3. Extends the Class ‘a” in New Class ‘b’ And Create a Method ftoc( ) And Call
the Method ipo( ).
4. Create Another Class ‘c’ Extends Class ‘b’ And Create Method disp( ).
5. In disp( ) Call the Method ftoc( ).
6. In Main Method Create An Object For c As c1 And Call the Method disp( ).
7. Display the Result.
8. Stop.

15
PROGRAM

import java.io.*;

class a

int po;

void ipo() throws IOException

InputStreamReader r = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(r);

po=Integer.parseInt(br.readLine());

class b extends a

void ftoc() throws IOException

ipo();

double kil=po*0.4536;

System.out.println("\n Kilogram : "+kil);

16
class c extends b

void disp() throws IOException

System.out.println("\n -: Pound To Kilogram Conversion :-\n");

System.out.print("\n Enter Pound : ");

ftoc();

}}

class mulinhr

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

c c1=new c();

c1.disp();

17
OUTPUT

D:\ Java >javac mulinhr.java

D:\ Java>java mulinhr

-: Pound To Kilogram Conversion :-

Enter Pound : 5

Kilogram : 2.268

RESULT

Thus the above Multilevel Inheritance Program has been implemented and executed Successfully.

18
EX. NO:5a
Implementation of Interfaces using Java.

AIM

To write a program implementing Interfaces concept in java

PROCEDURE

1. Create a Class Named As stud With Two Methods getno(int) & putno ( ).
2. Extends the Class stud in New Class test And Create a Methods
getmrk(float,float) & putmrk( ).
3. Create An Interface sports Declare putwt( ) Method
4. Create Another Class result Extends test And Implements sports.
5. In result Call the Methods And Define the Method putwt( ).
6. In Main Method Read Create Object For result And Call the Methods
getno(1234),getmrk(67.6,87.5) & disp().
7. Display the Result.
8. Stop the Program.

19
PROGRAM

class stud

int rno;

void getno(int n)

rno = n;

void putno()

System.out.println("Roll No : " + rno);

class test extends stud

float p1,p2;

void getmrk(float m1, float m2)

p1 = m1;

p2 = m2;

20
void putmrk()

System.out.println("Marks obtained ");

System.out.println("Part1 = " +p1);

System.out.println("Part2 = " +p2); }

interface sports

float spwt = 6.0f;

void putwt();

class results extends test implements sports

float tot;

public void putwt()

System.out.println("Sports wt = " +spwt);

void disp()

tot = p1 + p2 + spwt;

putno();

21
putmrk();

putwt();

System.out.println("Total Marks = " +tot);

}}

class multiple

public static void main(String aa[])

results std = new results();

System.out.println("Pass the Values As No=1234 MARKS=67.6,87.5

Weight=6.0 ");

std.getno(1234);

std.getmrk(67.6f,87.5f);

std.disp();

22
OUTPUT

D:\Java >javac multiple.java

D:\Java >java multiple

Pass the Values As No=1234 MARKS=67.6, 87.5 Weight=6.0

Roll No : 1234

Marks obtained

Part1 = 67.6

Part2 = 87.5

Sports wt = 6.0

Total Marks = 161.1

RESULT

Thus the Above Multiple Inheritance Program has been executed successfully.

23
EX. NO:5b
Implementation of Packages using Java.

AIM

To Write a Java Program Working With Package And Imports the Package Classes to Outside of the
Classes.

PROCEDURE

1. Create a Package Named As “student”.

2. In student Create a Class Named as vh With Method Called in( ).

3. In in( ) Method Reads the Values.

4. .Create Another Class Named as ‘stud’ And Imports the Package student Store the Class

Outside of the Package.

5. In stud Class Create An Object For vh As v and Call the Method in( ).

6. Display the Values.

7. Stop the Program.

24
PROGRAM

package student;

import java.io.*;

public class vh

InputStreamReader r = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(r);

public String name,no;

public void in() throws IOException

System.out.print("\n Enter the Student Name : ");

name = br.readLine();

System.out.print("\n Enter the VHC No : ");

no = br.readLine();

25
import student.vh;

import java.io.*;

public class stud

public static void main(String arg[]) throws IOException

vh v = new vh();

v.in();

System.out.println("\n NAME : "+ v.name);

System.out.println("\n VHC No : "+ v.no);

26
OUTPUT

RESULT

Thus the above Package Program has been implemented and executed Successfully.

27
EX. NO:6
Implementation of Abstract Class in Java.

AIM

To Write a Java Program implementing Abstract class in Java.

PROCEDURE

1. Start

2. Create an abstract class named shape that contains two integers and an empty method named

printarea().

3. Provide three classes named rectangle, triangle and circle such that each one of the classes extends the
class Shape.

4. Each of the inherited class from shape class should provide the implementation for the method

printarea().

5. Get the input and calculate the area of rectangle, circle and triangle.

6. In the shapeclass, create the objects for the three inherited classes and invoke the methods and display

the area values of the different shapes.

7. Stop.

28
PROGRAM

import java.util.*;

abstract class shape

int a,b;

abstract public void printarea();

class rectangle extends shape

public int area_rect;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("Enter the length and breadth of rectangle");

a=s.nextInt();

b=s.nextInt();

area_rect=a*b;

System.out.println("Length of rectangle: "+a +"breadth of rectangle: "+b);

System.out.println("The area of rectangle is:"+area_rect);

29
class triangle extends shape

double area_tri;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("Enter the base and height of triangle:");

a=s.nextInt();

b=s.nextInt();

System.out.println("Base of triangle: "+a +"height of triangle: "+b); area_tri=(0.5*a*b);

System.out.println("The area of triangle is:"+area_tri);

class circle extends shape

double area_circle;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("Enter the radius of circle:");

a=s.nextInt();

area_circle=(3.14*a*a);

System.out.println("Radius of circle:"+a);

System.out.println("The area of circle is:"+area_circle);

}}

30
public class Shapeclass

public static void main(String[] args)

rectangle r=new rectangle();

r.printarea();

triangle t=new triangle();

t.printarea();

circle r1=new circle();

r1.printarea();

31
OUTPUT

32
EX. NO:7
Write a Java Program using Exception Handling

AIM

To Write a Java Program implementing Exception Handling

PROCEDURE

1. Start

2. Create a class NegativeAmtException which extends Exception class.

3. Create a constructor which receives the string as argument.

4. Get the Amount as input from the user.

5. If the amount is negative, the exception will be generated.

6. Using the exception handling mechanism , the thrown exception is handled by the catch construct.

7. After the exception is handled , the string “invalid amount “ will be displayed.

8. If the amount is greater than 0, the message “Amount Deposited “ will be displayed

9. Stop.

33
PROGRAM

import java.util.*;

class NegativeAmtException extends Exception{

String msg; NegativeAmtException(String msg){

this.msg=msg;

public String toString(){

return msg;

}}

public class userdefined

public static void main(String[] args){

Scanner s=new Scanner(System.in); System.out.print("Enter Amount:"); int a=s.nextInt();

try

if(a<0)

throw new NegativeAmtException("Invalid Amount");

System.out.println("Amount Deposited");

catch(NegativeAmtException e){

System.out.println(e);

}}}

34
OUTPUT

RESULT

Thus the Java program to implement user defined exception handling has been implemented and
executed successfully.

35
EX. NO:8
Implementation of I/O Streams in Java Interface

AIM

To write a java program that reads a file name from the user, displays information about

whether the file exists, whether the file is readable, or writable, the type of file and the length of the file in
bytes.

PROCEDURE

1.Start

2.Create a class filedemo. Get the file name from the user.

3.Use the file functions and display the information about the file.

4.getName() displays the name of the file.

5.getPath() diplays the path name of the file.

6.getParent () -This method returns the pathname string of this abstract pathname’s parent, or

7.null if this pathname does not name a parent directory.

8.exists() – Checks whether the file exists or not.

9.canRead()-This method is basically a check if the file can be read.

10.canWrite()-verifies whether the application can write to the file.

11.isDirectory() – displays whether it is a directory or not.

12.isFile() – displays whether it is a file or not.

13.lastmodified() – displays the last modified information.

14.length()- displays the size of the file.

15.delete() – deletes the file

16. Invoke the predefined functions to display the information about the file.

17. Stop.

36
PROGRAM

import java.io.*;

import java.util.*;

class filedemo

public static void main(String args[])

String filename;

Scanner s=new Scanner(System.in);

System.out.println("Enter the file name ");

filename=s.nextLine();

File f1=new File(filename);

System.out.println("******************");

System.out.println("FILE INFORMATION");

System.out.println("******************");

System.out.println("NAME OF THE FILE "+f1.getName());

System.out.println("PATH OF THE FILE "+f1.getPath());


System.out.println("PARENT"+f1.getParent());

if(f1.exists())

System.out.println("THE FILE EXISTS ");

else

System.out.println("THE FILE DOES NOT ExISTS ");

if(f1.canRead())

System.out.println("THE FILE CAN BE READ ");

else

37
System.out.println("THE FILE CANNOT BE READ ");

if(f1.canWrite())

System.out.println("WRITE OPERATION IS PERMITTED");

else

System.out.println("WRITE OPERATION IS NOT PERMITTED");

if(f1.isDirectory())

System.out.println("IT IS A DIRECTORY ");

else

System.out.println("NOT A DIRECTORY");

if(f1.isFile())

System.out.println("IT IS A FILE ");

else

System.out.println("NOT A FILE");

System.out.println("File last modified "+ f1.lastModified());

System.out.println("LENGTH OF THE FILE "+f1.length());

System.out.println("FILE DELETED "+f1.delete());

38
OUTPUT

RESULT

Thus the java program to display file information has been implemented and executed successfully.

EX. NO:9 Implementation of Multithreaded Programming using Java

39
AIM

To write a java program that implements a multi-threaded application.

PROCEDURE

1.Start

2.Create a class even which implements first thread that computes the square of the number .

3.run() method implements the code to be executed when thread gets executed.

4.Create a class odd which implements second thread that computes the cube of the number.

5.Create a third thread that generates random number. If the random number is even, it displays the
square of the number. If the random number generated is odd, it displays the cube of the given number.

6.The Multithreading is performed and the task switched between multiple threads.

7.The sleep () method makes the thread to suspend for the specified time.

8.Stop.

PROGRAM

import java.util.*;

40
class even implements Runnable

public int x; public even(int x)

this.x = x;

public void run()

System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);

class odd implements Runnable

public int x; public odd(int x)

this.x = x;

public void run()

System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);

class A extends Thread{

public void run(){

int num = 0;

41
Random r = new Random(); try

for (int i = 0; i < 5; i++){

num = r.nextInt(100);

System.out.println("Main Thread and Generated Number is " + num);

if (num % 2 == 0){

Thread t1 = new Thread(new even(num));

t1.start();

else{

Thread t2 = new Thread(new odd(num)); t2.start();

Thread.sleep(1000);

System.out.println("-----------------------------------");

}}

catch (Exception ex){

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

public class multithreadprog

public static void main(String[] args)

A a = new A(); a.start();}}

OUTPUT

42
RESULT

Thus the Java program for multi-threaded application has been implemented and executed successfully.

43
EX. NO:10 Implementation of Generic Function in Java Interface

AIM

To write a java program to print different type of array using a single Generic function.

PROCEDURE

1. start

2. Create one dimensional arrays of specific data types and initialize them with values.

3. Pass the array of specific data types to a single generic function.

4. Create a generic function which supports all the different data typed arrays.

5. Iterate using loops to print all the elements of the array.

6. Stop.

44
PROGRAM

public class GenericsExample

public static void main(String args[])

Integer[] intArray={1,2,3,4,5};

Double[] doubleArray={5.5,4.4,3.3,2.2,1.1};

Character[] charArray={'H','E','L','L','O'};

String[] stringArray={"B","Y","E"};

displayArray(intArray);

displayArray(doubleArray);

displayArray(charArray);

displayArray(stringArray);

public static <T>void displayArray(T[] array)

for(T temp : array)

System.out.print(temp+" ");

System.out.println();

45
OUTPUT

RESULT

Thus the Java program to print different type of array elements using a generic function has been
implemented and executed successfully.

46
EX. NO:11a Implementation of AWT controls and Event classes using Java Program.

AIM
To develop an AWT Applet program using Buttons and Controls.

PROCEDURE

1. Start the program.

2. Import the Header Files awt, awt.event .

3. Create a Class that Extends Applet and Implements ActionListener.

4. Set the Layout and add necessary Text field, Labels and Buttons.

5. Add the AWT controls to the Applet Container.

6. Implement and override the ActionListener interface method.

7. Write the code to perform necessary operation.

8. Compile and Execute the Program.

9. Stop the Program.

47
PROGRAM

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<applet code="Arith.class" width=500 height=500></applet>*/

public class Arith extends Applet implements ActionListener

Button b1,b2,b3,b4;

Label l1,l2,l3;

TextField t1,t2,t3;

String s1,s2;

int a,b,c;

public void init()

setLayout(new GridLayout(5,2));

l1=new Label("Enter 1st Number",l1.LEFT);

l2=new Label("Enter 2nd Number",l2.LEFT);

l3=new Label("Result",l3.LEFT);

add(l1);

t1=new TextField(20);

add(t1);

48
add(l2);

t2=new TextField(20);

add(t2);

add(l3);

t3=new TextField(20);

add(t3);

b1=new Button("ADDITION");

add(b1);

b2=new Button("SUBTRACTION");

add(b2);

b3=new Button("MULTIPLICATION");

add(b3);

b4=new Button("DIVISION");

add(b4);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

49
public void actionPerformed(ActionEvent ae)

s1=t1.getText();

s2=t2.getText();

a=Integer.parseInt(s1);

b=Integer.parseInt(s2);

if(ae.getSource()==b1)

c=a+b;

else if(ae.getSource()==b2)

c=a-b;

else if(ae.getSource()==b3)

c=a*b;

else if(ae.getSource()==b4)

c=a/b;

t3.setText(""+c);

}}

50
OUTPUT

RESULT
Thus the above program has been implemented and executed Successfully.

51
EX. NO:11b Implementation of AWT controls and Event classes using Java Program.

AIM
To develop an AWT Applet program using Event classes.

PROCEDURE

1. Start the program.

2. Import the Header Files awt, awt.event and Swing .

3. Create a Class that Extends Frame and Implements MouseListener.

4. Create Panel,set the Layout and add necessary Text field, Labels and Buttons.

5. Implement and override the MouseListener interface methods.

6. Write the code to perform necessary operation.

7. Compile and Execute the Program.

8. Stop the Program.

52
//Java program to handle MouseListener events

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class mouseex extends Frame implements MouseListener {

// Jlabels to display the actions of events of mouseListener

static JLabel label1, label2, label3;

// default constructor

mouseex(){ }

// main class

public static void main(String[] args)

// create a frame

JFrame f = new JFrame("MouseListener");

// set the size of the frame

f.setSize(600, 100);

// close the frame when close button is pressed

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create anew panel

JPanel p = new JPanel();

// set the layout of the panel

p.setLayout(new FlowLayout());

// initialize the labels


53
label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

// create an object of mouse class

mouseex m = new mouseex();

// add mouseListener to the frame

f.addMouseListener(m);

// add labels to the panel

p.add(label1);

p.add(label2);

p.add(label3);

// add panel to the frame

f.add(p);

f.show();

// getX() and getY() functions return the

// x and y coordinates of the current

// mouse position

// getClickCount() returns the number of

// quick consecutive clicks made by the user

// this function is invoked when the mouse is pressed

54
public void mousePressed(MouseEvent e)

// show the point where the user pressed the mouse

label1.setText("mouse pressed at point:" + e.getX() + " " + e.getY());

// this function is invoked when the mouse is released

public void mouseReleased(MouseEvent e)

// show the point where the user released the mouse click

label1.setText("mouse released at point:"+ e.getX() + " " + e.getY());

// this function is invoked when the mouse exits the component

public void mouseExited(MouseEvent e)

// show the point through which the mouse exited the frame

label2.setText("mouse exited through point:"+ e.getX() + " " + e.getY());

// this function is invoked when the mouse enters the component

public void mouseEntered(MouseEvent e)

{
55
// show the point through which the mouse entered the frame

label2.setText("mouse entered at point:"+ e.getX() + " " + e.getY());

// this function is invoked when the mouse is pressed or released

public void mouseClicked(MouseEvent e)

// getClickCount gives the number of quick,

// consecutive clicks made by the user

// show the point where the mouse is i.e

// the x and y coordinates

label3.setText("mouse clicked at point:"+ e.getX() + " "+ e.getY() + "mouse clicked :" +
e.getClickCount());

56
OUTPUT

RESULT
Thus the above program has been implemented and executed Successfully.

57
EX. NO:12 Develop a miniproject for any application using JDBC

AIM:
To develop a Query application with database connectivity

PROCEDURE:

1. Start the program.

2. Import the Header Files awt, awt.event and sql .

3. Create a Class that Extends Frame and Implements ActionListener.

4. Create Panel,set the Layout and add necessary Text field, Labels and Buttons.

5. Implement and override the ActionListener interface methods.

6. Write the necessary logic and code for database connectivity.

7. Compile and Execute the Program.

8. Stop the Program.

58
PROGRAM

import java.sql.*;

import java.awt.*;

import java.awt.event.*;

public class PreparedQueryApp extends Frame implements ActionListener

TextField pid;

TextField pname;

Button query;

Panel p;

static ResultSet result;

static Connection con;

static PreparedStatement stat;

public PreparedQueryApp()

super("The query application");

setLayout(new GridLayout(5,1));

pid=new TextField(20);

pname=new TextField(50);

query=new Button("Query");

59
p=new Panel();

add(new Label("Publisher ID:"));

add(pid);

add(new Label("Publisher Name:"));

add(pname);

add(p);

p.add(query);

query.addActionListener(this);

pack();

setVisible(true);

public static void main(String args[])

PreparedQueryApp obj=new PreparedQueryApp();

try

Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver loaded");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dsn","root","ad
min");

System.out.println("connected");

stat=con.prepareStatement("select * from publishers where


pub_id=?"); }

60
catch(Exception e)

System.out.println("Error"+e);

obj.showRecord(result);

public void actionPerformed(ActionEvent event)

if(event.getSource()==query)

try

stat.setString(1,pid.getText());

result=stat.executeQuery();

result.next();

catch(Exception e) {

showRecord(result);

}
61
}

public void showRecord(ResultSet result)

try

pid.setText(result.getString(1));

pname.setText(result.getString(2));

catch(Exception e)

62
OUTPUT

mysql> create database dsn;

mysql> use dsn;

mysql> create table publishers(pub_id varchar(10),pub_name varchar(10));

mysql> insert into publisher values(‘100’,’tata’);

mysql> insert into publisher values(‘200’,’cengage’);

63
64
RESULT
Thus the above Query application miniproject has been Executed Successfully.

ADDITIONAL LAB PROGRAMS

EX. NO:13 To Develop a Student Information System

AIM

To Develop a Student Information System

PROCEDURE

1. Start the program.

2. Import necessary Header Files.

3. Create a Class with methods that perform registration, password, updation,

deletion, searching and exit operations.

4. Write the necessary logic and code for database connectivity.

5. Compile and Execute the Program.

6. Stop the Program.

65
PROGRAM

//democlass.java

import java.sql.*;

import java.util.Scanner;

public class democlass {

public static void main(String[] args) throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException{

try

{ int choice=0;

student s = new student();

do

System.out.println("Select an operation \n 1- Registration \n 2- Password Update \n 3- Delete a


Record \n 4- Search for a Student \n 5- Exit");

Scanner choicein = new Scanner(System.in);

System.out.println("Enter your choice:");

choice=choicein.nextInt();

switch(choice)

case 1:

s.getStudentDetails();

s.insertStudent();

break;

case 2:

66
s.updateStudentPassword();

break;

case 3:

s.deleteStudentRecord();

break;

case 4:

s.searchStudent();

break;

case 5:

break;

default:

System.out.println("Select the correct choice");

}while(choice!=5);

System.out.println("Thanks for Using our Software");

catch(Exception e)

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

67
class student

private String name;

private String password;

private String country;

private int mark;

public void getStudentDetails() {

Scanner input = new Scanner(System.in);

System.out.println("Enter your Name");

name = input.nextLine();

System.out.println("Enter your password");

password = input.nextLine();

System.out.println("Enter your Country");

country = input.nextLine();

System.out.println("Enter the mark");

mark = input.nextInt();

public void insertStudent() throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException {

//here we are going to work with a database

//we need to open a database connection1

68
dbmsconnection dbmsconnect = new
dbmsconnection("jdbc:oracle:thin:@localhost:1521:XE","sakthi","sakthi");

System.out.println("oracle started");

Connection con = dbmsconnect.getConnection();

String sql = "insert into student values(?,?,?,?)";

PreparedStatement stmt = con.prepareStatement(sql);

stmt.setString(1, name);

stmt.setString(2, password);

stmt.setString(3, country);

stmt.setInt(4, mark);

int i = stmt.executeUpdate();

System.out.println("Record inserted successfully");

dbmsconnect.closeConnection(con, stmt);

public void updateStudentPassword() throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException {

dbmsconnection dbmsconnect = new


dbmsconnection("jdbc:oracle:thin:@localhost:1521:XE","sakthi","sakthi");

Connection con = dbmsconnect.getConnection();

System.out.println("Enter Your Name");

Scanner input = new Scanner(System.in);

String inputname=input.nextLine();

System.out.println("Enter the new Password");

String inputpass=input.nextLine();

String sql = "update student set password = ? where name = ?";

69
PreparedStatement stmt = con.prepareStatement(sql);

stmt.setString(1, inputpass);

stmt.setString(2, inputname);

int i = stmt.executeUpdate();

if(i>0)

System.out.println("Record updated sucessfully");

}else

System.out.println("No Such record in the Database");

dbmsconnect.closeConnection(con, stmt);

public void deleteStudentRecord() throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException {

dbmsconnection dbmsconnect = new


dbmsconnection("jdbc:oracle:thin:@localhost:1521:XE","sakthi","sakthi");

Connection con = dbmsconnect.getConnection();

System.out.println("Enter the Name of the Student");

Scanner input = new Scanner(System.in);

String inputname=input.nextLine();

String sql = "delete from student where name = ?";

PreparedStatement stmt = con.prepareStatement(sql);

stmt.setString(1, inputname);

int i = stmt.executeUpdate();

70
if(i>0)

System.out.println("Record Deleted Successfully");

else

System.out.println("No Such Record in the Database");

dbmsconnect.closeConnection(con, stmt);

public void searchStudent() throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException {

dbmsconnection dbmsconnect = new


dbmsconnection("jdbc:oracle:thin:@localhost:1521:XE","sakthi","sakthi");

Connection con = dbmsconnect.getConnection();

System.out.println("Enter Your Name");

Scanner input = new Scanner(System.in);

String inputname=input.nextLine();

String sql = "select * from student where name=?";

PreparedStatement stmt = con.prepareStatement(sql);

stmt.setString(1, inputname);

ResultSet rs = stmt.executeQuery();

if(rs.next()==false)

System.out.println("No such record found in the database");

71
}

else

System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));

dbmsconnect.closeConnection(con, stmt);

}}

class dbmsconnection

String url;

String username;

String password;

public dbmsconnection(String url, String username, String password) {

this.url = url;

this.username = username;

this.password = password;

public Connection getConnection() throws InstantiationException, IllegalAccessException,


ClassNotFoundException, SQLException {

Connection con=null;

Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

con = DriverManager.getConnection(url,username,password);

System.out.println("Connection Established Successfully");

return con;

public void closeConnection(Connection con,Statement stmt) throws SQLException

72
{

stmt.close();

con.close();

System.out.println("The connection is closed"); }}

OUTPUT

Database used: Oracle11g

Table creation:

SQL> create table student(name varchar2(10),password varchar2(10),country varchar2(10),mark

number(10));

Table created.

SQL> desc student;

Name Null? Type

----------------------------------------- -------- ----------------------------

NAME VARCHAR2(10)

PASSWORD VARCHAR2(10)

COUNTRY VARCHAR2(10)

MARK NUMBER(10)

73
Microsoft Windows [Version 6.3.9600]

(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Students>d:

D:\>cd javapro

D:\javapro>path=C:\Program Files\Java\jdk1.8.0\bin;

D:\javapro>set classpath=%classpath%;C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar;

D:\javapro>javac democlass.java

D:\javapro>java democlass

Select an operation

1- Registration

2- Password Update

3- Delete a Record

4- Search for a Student

5- Exit

74
Enter your choice:

Enter your Name

sakthi

Enter your password

sa

Enter your Country

india

Enter the mark

85

oracle started

Connection Established Successfully

Record inserted successfully

The connection is closed

Select an operation

1- Registration

2- Password Update

3- Delete a Record

4- Search for a Student

5- Exit

Enter your choice:

75
Connection Established Successfully

Enter Your Name

sakthi

Enter the new Password

sakthi123

Record updated sucessfully

The connection is closed

Select an operation

1- Registration

2- Password Update

3- Delete a Record

4- Search for a Student

5- Exit

Enter your choice:

Connection Established Successfully

Enter Your Name

sakthi

sakthi sakthi123 india 85

The connection is closed

76
RESULT
Thus the student information system has been Executed Successfully.

EX. NO:14 Implement producer consumer problem using threads.


DATE:

AIM

To write a producer consumer problem using threads.

PROCEDURE

1. Start

2. Enter the number of producers and consumers.

3. The producer produces the job and put it in the buffer.

4. The consumer takes the job from the buffer.

5. If the buffer is full the producer goes to sleep.

6. If the buffer is empty then consumer goes to sleep.

7. Stop.

77
PROGRAM:

public class ProducerConsumerTest {

public static void main(String[] args) {

CubbyHole c = new CubbyHole();

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

p1.start();

c1.start(); }}

class CubbyHole

private int contents;

private boolean available =false;

public synchronized int get() {

while (available == false) {

try {

wait();

} catch (InterruptedException e) {}

available = false;

notifyAll();

return contents;

78
public synchronized void put(int value) {

while (available == true)

try {

wait();

} catch (InterruptedException e) { }

contents = value;

available = true; notifyAll();

}}

class Consumer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

public void run() {

int value = 0;

for (int i = 0; i < 10; i++) {

value = cubbyhole.get();

79
System.out.println("Consumer #" + this.number + " got: " + value);

} }}

class Producer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Producer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

public void run() {

for (int i = 0; i < 10; i++) { cubbyhole.put(i);

System.out.println("Producer #" + this.number + " put: " + i);

try {

sleep((int)(Math.random() * 100));

} catch (InterruptedException e) { }

80
OUTPUT:

Producer #1 put: 0

Consumer #1 got: 0

Producer #1 put: 1

Consumer #1 got: 1

Producer #1 put: 2

Consumer #1 got: 2

Producer #1 put: 3

Consumer #1 got: 3

Producer #1 put: 4

Consumer #1 got: 4

Producer #1 put: 5

Consumer #1 got: 5

Producer #1 put: 6

Consumer #1 got: 6

Producer #1 put: 7

Consumer #1 got: 7

Producer #1 put: 8

Consumer #1 got: 8

Producer #1 put: 9

Consumer #1 got: 9

81
RESULT:

Thus the producer consumer problem using threads had been executed successfully.

82

You might also like