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

JAVA Lab Manual

Uploaded by

rohith11290
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

JAVA Lab Manual

Uploaded by

rohith11290
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY

(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)


Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

DEPARTMENT OF COMPUTER SCINCE AND ENGINEERING

JAVA PROGRAMMING
LAB MANUAL

Subject Code : CS408PC


Regulation : R18/JNTUH
Academic Year : 2019-2020
II B. TECH II SEMESTER

COMPUTER SCIENCE AND ENGINEERING


KG REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
Affiliated o JNTUH, Chilkur,(V), Moinabad(M) R. R Dist, TS-501504
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


VISION AND MISSION OF THE INSTITUTION
VISION:
To become self-sustainable institution this is recognized for its new age engineering through innovative teaching and
learning culture, inculcating research and entrepreneurial ecosystem, and sustainable social impact in the community.
MISSION:
 To offer undergraduate and post-graduate programs that is supported through industry relevant curriculum and
innovative teaching and learning processes that would help students succeed in their professional careers.
 To provide necessary support structures for students, this will contribute to their personal and professional growth
and enable them to become leaders in their respective fields.
 To provide faculty and students with an ecosystem that fosters research and development through strategic
partnerships with government organisations and collaboration with industries.
 To contribute to the development of the region by using our technological expertise to work with nearby
communities and support them in their social and economic growth.

VISION AND MISSION OF CSE DEPARTMENT


VISION:
To be recognized as a department of excellence by stimulating a learning environment in which students and faculty
will thrive and grow to achieve their professional, institutional and societal goals.
MISSION:
 To provide high quality technical education to students that will enable life-long learning and build
expertise in advanced technologies in Computer Science and Engineering.
 To promote research and development by providing opportunities to solve complex engineering problems
in collaboration with industry and government agencies.
 To encourage professional development of students that will inculcate ethical values and leadership skills
while working with the community to address societal issues.
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

DEPARTMENT OF COMPUTERSCIENCEANDENGINEERING
PROGRAM EDUCATIONAL OBJECTIVES (PEOS):

A graduate of the Computer Science and Engineering Program should:


Program Educational Objective1: (PEO1)
PEO1 The Graduates will provide solutions to difficult and challenging issues in their profession
by applying computer science and engineering theory and principles.
Program Educational Objective2 :( PEO2)
PEO2 The Graduates have successful careers in computer science and engineering fields or will be
able to successfully pursue advanced degrees.
Program Educational Objective3: (PEO3)
PEO3 The Graduates will communicate effectively, work collaboratively and exhibit high levels of
Professionalism, moral and ethical responsibility.
Program Educational Objective4 :( PEO4)
PEO4 The Graduates will develop the ability to understand and analyse Engineering issues in a
broader perspective with ethical responsibility towards sustainable development.

PROGRAM OUTCOMES (POS):

Engineeringknowledge:Applytheknowledgeofmathematics,science,engineering
PO1
Fundamentals andanengineeringspecializationtothesolutionofcomplexengineeringproblems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
PO3
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Environment and sustainability: Understand the impact of the professional engineering


PO7 Solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
PO8
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader
PO9
In diverse teams, and in multi-disciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
PO10
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
PO11 Engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES(PSOs):

Problem Solving Skills – Graduate will be able to apply computational techniques and
PSO1
software principles to solve complex engineering problems pertaining to software engineering.
Professional Skills – Graduate will be able to think critically, communicate effectively, and
PSO2
collaborate in teams through participation in co and extra-curricular activities.
Successful Career – Graduates will possess a solid foundation in computer science and
PSO3 engineering that will enable them to grow in their profession and pursue lifelong learning
through post-graduation and professional development.
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

CONTENTS

S.No Name of the Experiment Page No.


1 Use Eclipse or Net bean platform and acquaint with the various menus. Create a
test project, add a test class, and run it. See how you can use auto suggestions,
auto fill. Try code formatter and code refactoring like renaming variables,
methods, and classes. Try debug step by step with a small program of about 10 to
15 lines which contains at least one if else condition and a for loop.
2 Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divided by zero.
3 a) Develop an applet in Java that displays a simple message.
b) Develop an applet in Java that receives an integer in one text field, and
computes its factorial Value and returns it in another text field, when the button
named “Compute” is clicked.
4 Write a Java program that creates a user interface to perform integer divisions.
The user enters two numbers in the text fields, Num1 and Num2. The division of
Num1 and Num 2 is displayed in the Result field when the Divide button is
clicked. If Num1 or Num2 were not an integer, the program would throw a
Number Format Exception. If Num2 were Zero, the program would throw an
Arithmetic Exception. Display the exception in a message dialog box.
5 Write a Java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and 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
6 Write a Java program for the following: Create a doubly linked list of elements.
Delete a given element from the above list. Display the contents of the list after
deletion.
7 Write a Java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green with radio buttons. On selecting a
button, an appropriate message with “Stop” or “Ready” or “Go” should appear
above the buttons in selected color. Initially, there is no message shown.
8 Write a Java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). Provide three classes named
Rectangle, Triangle, and Circle such that each one of the classes extends the
class Shape. Each one of the classes contains only the method print Area () that
prints the area of the given shape.
9 Suppose that a table named Table.txt is stored in a text file. The first line in the
file is the header, and the remaining lines correspond to rows in the table. The
elements are separated by commas. Write a java program to display the table
using Labels in Grid Layout.
10 Write a Java program that handles all mouse events and shows the event name at
the center of the window when a mouse event is fired (Use Adapter classes).
11 Write a Java program that loads names and phone numbers from a text file where
the data is organized as one line per record and each field in a record are
separated by a tab (\t). It takes a name or phone number as input and prints the
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

corresponding other value from the hash table (hint: use hash tables).

12 Write a Java program that correctly implements the producer – consumer problem
using the concept of interthread communication.
13 Write a Java program to list all the files in a directory including the files present
in all its subdirectories
14 Write a Java program that implements Quick sort algorithm for sorting a list of
names in ascending order
15 Write a Java program that implements Bubble sort algorithm for sorting in
descending order and also shows the number of interchanges occurred for the
given set of integers.

Additional Programs

S No List of the Experiment Page No


1 Write a java program that connects to a database using JDBC
2 Write a java program to connect to a database using JDBC and insert values into it
3 Write a java program to connect to a database using JDBC and delete values from it
4 Write a java program for handling Mouse events and Key events
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

1. Use eclipse or Netbean platform and acquaint with the various menus, create a test project,
add a test class and run it see how you can use auto suggestions, auto fill. Try code formatter
and code refactoring like renaming variables, methods and classes. Try debug step by step
with a small program of about 10 to 15 lines which contains at least one if else condition and
a for loop.
Program:-
public class Prog1
{
public static void main(String[] args)
{
System.out.println("\n Prog. is showing even no"); for(int
i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n "+i);
}
}
}
}

Output:-
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

2. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +, -,*, % operations. Add a text field to display the result. Handle
any possible exceptions like divide by zero.
Program:-

Importjava.awt.*;
importjava.awt.event.*;
publicclass Calculator implements ActionListener
{
intc,n;
String s1,s2,s3,s4,s5;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextFieldtf;
GridLayoutg;
Calculator()
{
f = newFrame("My calculator");
p = newPanel();
f.setLayout(newFlowLayout());
b1 = newButton("0");
b1.addActionListener(this);
b2 = newButton("1");
b2.addActionListener(this);
b3 = newButton("2");
b3.addActionListener(this);
b4 = newButton("3");
b4.addActionListener(this);
b5 = newButton("4");
b5.addActionListener(this);
b6 = newButton("5");
b6.addActionListener(this);
b7 = newButton("6");
b7.addActionListener(this);
b8 = newButton("7");
b8.addActionListener(this);
b9 = newButton("8");
b9.addActionListener(this);
b10 = newButton("9");
b10.addActionListener(this);
b11 = newButton("+");
b11.addActionListener(this);
b12 = newButton("-");
b12.addActionListener(this);
b13 = newButton("*");
b13.addActionListener(this);
b14 = newButton("/");
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

b14.addActionListener(this);
b15 = newButton("%");
b15.addActionListener(this);
b16 = newButton("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this);
tf = newTextField(20);
f.add(tf);
g = newGridLayout(4,4,10,20);
p.setLayout(g);
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);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
publicvoidactionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;

}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
publicstaticvoidmain(String[] abc)
{
Calculator v = newCalculator();
}
}

Output:-
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

3) a) Develop an applet that displays a simple message.

Program:-

import java.awt.*; import

java.applet.*;

/*<applet code = “HelloJava” width = 200 height = 60 > </applet>*/ public

class HelloJava extends Applet {

public void paint(Graphics g) {

g.drawString(“Hello Java”, 10, 100);


}
}

Output:-
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

3.b) Develop an Applet that receives an integer in one text field & compute its factorial value &
returns it
in another text filed when the button “Compute” is clicked.

Program:-

import java.awt.*; import

java.lang.String; import

java.awt.event.*;

import java.applet.Applet;

public class Fact extends Applet implements ActionListener

String str; Button b0;

TextField t1,t2; Label l1;

public void init(){ Panel p=new

Panel();

p.setLayout(new GridLayout());

add(new Label("Enter any Integer value")); add(t1=new

TextField(20));

add(new Label("Factorial value is: ")); add(t2=new

TextField(20));

add(b0=new Button("compute"));

b0.addActionListener(this);

public void actionPerformed(ActionEvent e)

int i,n,f=1;
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)

f=f*i;

t2.setText(String.valueOf(f)); repaint();

Output:-

4. Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is
displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

an integer, the program would throw a NumberFormatException. If Num2 were Zero, the
program would throw an Arithmetic Exception Display the exception in a message dialog
box.

Program:-
import java.awt.*; import
java.awt.event.*; import
java.applet.*;
public class Add1 extends Applet implements ActionListener
{
String msg;
TextField num1, num2, res; Label l1, l2,
l3;
Button div; public void init()
{
l1 = new Label("Number 1"); l2 = new
Label("Number 2"); l3 = new
Label("result"); num1 = new
TextField(10); num2 = new
TextField(10); res = new TextField(30);
div = new Button("DIV");
div.addActionListener(this); add(l1);
add(num1); add(l2);
add(num2); add(l3);
add(res);
add(div);
}

public void actionPerformed(ActionEvent ae)


{
String arg = ae.getActionCommand(); if
(arg.equals("DIV"))
{
String s1 = num1.getText(); String s2 =
num2.getText();
int num1 = Integer.parseInt(s1);

int num2 = Integer.parseInt(s2); if (num2


== 0)
{
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

msg = "Arithemetic Exception "; repaint();


}
else if ((num1 < 0) || (num2 < 0))
{
msg = "NumberFormat Exception"; repaint();
}
else
{
int num3 = num1 / num2; msg =
String.valueOf(num3);
}
res.setText(msg);
}
}
public void paint(Graphics g)
{
//g.drawString(msg, 30, 70);
}
}

APPLET.HTML

<html>

<head>

</head>

<body>

/*<applet code="Add1.class"width=350 height=300>

</applet>*/

</body>

</html>

Output:-
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

5.) Write a java program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and 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.
Program:-

import java.util.Random;

class RandomNumberThread extends Thread {


public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
21
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

class SquareThread extends Thread {


int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + (number * number));
}
}

class CubeThread extends Thread {


int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class MultiThreadingTest {


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

22
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Output:

23
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

6. Write a Java program for the following:


Create a doubly linked list of elements.
Delete a given element from the above list.
Display the contents of the list after deletion.

// Java program to delete a node from


// Doubly Linked List

// Class for Doubly Linked List


public class DLL {
Node head; // head of list

/* Doubly Linked list Node*/


class Node {
int data;
Node prev;
Node next;

// Constructor to create a new node


// next and prev is by default initialized
// as null
Node(int d) { data = d; }
}

// Adding a node at the front of the list


public void push(int new_data)
{
// 1. allocate node
// 2. put in the data
Node new_Node = new Node(new_data);

// 3. Make next of new node as head


// and previous as NULL
new_Node.next = head;
new_Node.prev = null;

// 4. change prev of head node to new node


if (head != null)
head.prev = new_Node;

// 5. move the head to point to the new node


head = new_Node;
}

// This function prints contents of linked list


24
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

// starting from the given node


public void printlist(Node node)
{
Node last = null;

while (node != null) {


System.out.print(node.data + " ");
last = node;
node = node.next;
}

System.out.println();
}

// Function to delete a node in a Doubly Linked List.


// head_ref --> pointer to head node pointer.
// del --> data of node to be deleted.
void deleteNode(Node del)
{

// Base case
if (head == null || del == null) {
return;
}

// If node to be deleted is head node


if (head == del) {
head = del.next;
}

// Change next only if node to be deleted


// is NOT the last node
if (del.next != null) {
del.next.prev = del.prev;
}

// Change prev only if node to be deleted


// is NOT the first node
if (del.prev != null) {
del.prev.next = del.next;
}

// Finally, free the memory occupied by del


return;
}

// Driver Code
public static void main(String[] args)
25
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOG Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

{
// Start with the empty list
DLL dll = new DLL();

// Insert 2. So linked list becomes 2->NULL


dll.push(2);

// Insert 4. So linked list becomes 4->2->NULL


dll.push(4);

// Insert 8. So linked list becomes 8->4->2->NULL


dll.push(8);

// Insert 10. So linked list becomes 10->8->4->2->NULL


dll.push(10);

System.out.print("Created DLL is: ");


dll.printlist(dll.head);

// Deleting first node


dll.deleteNode(dll.head);

// List after deleting first node


// 8->4->2
System.out.print("\nList after deleting first node: ");
dll.printlist(dll.head);

// Deleting middle node from 8->4->2


dll.deleteNode(dll.head.next);

System.out.print("\nList after Deleting middle node: ");


dll.printlist(dll.head);
}
}

Output:

Original Linked list 10 8 4 2


Modified Linked list 8

26
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

7. Write a Java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with “Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially, there is no message
shown.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
* <applet code = "TrafficLightsExample" width = 1000 height = 500>
* </applet>
* */

public class TrafficLightsExample extends Applet implements ItemListener{

CheckboxGroup grp = new CheckboxGroup();


Checkbox redLight, yellowLight, greenLight;
Label msg;
public void init(){
redLight = new Checkbox("Red", grp, false);
yellowLight = new Checkbox("Yellow", grp, false);
greenLight = new Checkbox("Green", grp, false);
msg = new Label("");

redLight.addItemListener(this);
yellowLight.addItemListener(this);
greenLight.addItemListener(this);

add(redLight);
add(yellowLight);
27
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

add(greenLight);
add(msg);
msg.setFont(new Font("Serif", Font.BOLD, 20));
}
public void itemStateChanged(ItemEvent ie) {
redLight.setForeground(Color.BLACK);
yellowLight.setForeground(Color.BLACK);
greenLight.setForeground(Color.BLACK);

if(redLight.getState() == true) {
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
}
else if(yellowLight.getState() == true) {
yellowLight.setForeground(Color.YELLOW);
msg.setForeground(Color.YELLOW);
msg.setText("READY");
}
else{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN);
msg.setText("GO");
}
}
}

28
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

29
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

8. Write a Java program to create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only
the method print Area () that prints the area of the given shape.

import java.util.*;

abstract class Shape {


int length, breadth, radius;

Scanner input = new Scanner(System.in);

abstract void printArea();

class Rectangle extends Shape {


void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
} 30

}
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

class Cricle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");

System.out.print("Enter Radius: ");


radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Rectangle rec = new Rectangle();
rec.printArea();

Triangle tri = new Triangle();


tri.printArea();

Cricle cri = new Cricle();


cri.printArea();
}
}

Output:

31
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header,
and the remaining lines correspond to rows in the table. The elements are separated by commas.
Write a java program to display the table using Labels in Grid Layout.

Source code:

import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;

class A extends JFrame {


public A() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new
FileInputStream("C:\\Users\\User\\eclipse-workspace\\LabManual\\src\\HashTab.txt");
Scanner sc = new Scanner(fin).useDelimiter(",");
String[] arrayList;
String a;
while (sc.hasNextLine()) {
a = sc.nextLine(); arrayList =
a.split(","); for (String i : arrayList) {
add(new JLabel(i));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
pack(); 32
setVisible(true);
}
}
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

public class TableTest {

public static void main(String[] args) {


A a = new A();
}
}

Output:

33
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

10. Write a Java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired (Use Adapter classes).

Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code="MouseDemo" width=300 height=300>


</applet>*/
public class MouseDemo extends Applet implements MouseListener, MouseMotionListener { int mx = 0;
int my = 0;
String msg = "";

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me) {


mx = 20;
my = 40;
msg = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent me) {


mx = 30;
my = 60;
msg = "Mouse Pressed"; 34
repaint();
}

public void mouseReleased(MouseEvent me) {


KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

mx = 30;
my = 60;
msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Exited";
repaint();
}

public void mouseDragged(MouseEvent me) {


mx = me.getX();
my = me.getY();
showStatus("Currently mouse dragged" + mx + " " + my);

repaint();
}

public void mouseMoved(MouseEvent me) {


mx = me.getX();
my = me.getY();
showStatus("Currently mouse is at" + mx + " " + my); repaint();
}

public void paint(Graphics g) {


g.drawString("Handling Mouse Events", 30, 20);
g.drawString(msg, 60, 40);
}
}

Output:

35
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

11. Write a java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t).it takes a
name or phone number as input and prints the corresponding other value from the hash
table(hint: use hash tables)

Source code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashTab {


public static void main(String[] args) {
HashTab prog11 = new HashTab();
Hashtable<String, String> hashData = prog11.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n" + hashData); prog11.printTheData(hashData,
"raja"); prog11.printTheData(hashData, "123"); prog11.printTheData(hashData, " --- ");
}

private void printTheData(Hashtable<String, String> hashData, String input) { String output =


null;
if (hashData != null) {
Set<String> keys = hashData.keySet();
if (keys.contains(input)) {
output = hashData.get(input);
} else {
Iterator<String> iterator = keys.iterator(); while (iterator.hasNext())
{
String key = iterator.next();
String value = hashData.get(key);
if (value.equals(input)) {
output = key;
break;
}
}
}
}
System.out.println("Input given:" + input);
if (output != null) {
System.out.println("Data found in HashTable:" + output);
} else {
System.out.println("Data not found in HashTable");
}
}

36

private Hashtable<String, String> readFromFile(String fileName) { Hashtable<String, String>


hashData = new Hashtable<String, String>(); try {
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

File f = new File("D:\\java\\" + fileName);


BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while ((line = br.readLine()) != null) {

String[] details = line.split("\t");


hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return hashData;
}
}

Output:

37
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

12. Write a Java program that correctly implements the producer – consumer problem using the
concept of interthread communication.

Source Code:
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
} 38
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

public void run() {


int i = 0;
while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}

class ProducerConsumer{
public static void main(String args[]) { ItemQueue itemQueue
= new ItemQueue(); new Producer(itemQueue);
new Consumer(itemQueue);

}
}

Output:

39
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.

Source Code:

import java.util.Scanner;
import java.io.*;

public class ListingFiles {

public static void main(String[] args) {

String path = null;


Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: "); path =
read.next() + ":\\"; File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exists!"); printLine();
}
else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory(Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: "); path = path +
"\\\\" + read.next(); File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
System.out.println("The sub-directory does not exists!");
printLine();
int lastIndex = path.lastIndexOf("\\");
path = path.substring(0, lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}
public static void printFiles(String path) {
System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
40
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

System.out.println("> " + file.getName());


}
}
public static void printLine() {
System.out.println("- -");
}
}

Output:

14. Write a Java program that implements Quick sort algorithm for sorting a list of names 41
in ascending Order.

Source Code:
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

public class QuickSortOnStrings {

String names[];
int length;

public static void main(String[] args) { QuickSortOnStrings obj = new


QuickSortOnStrings();
String stringsList[] = {"raja", "gouthu", "rani", "gouthami", "honey", "heyaansh", "hello"};
obj.sort(stringsList);

for (String i : stringsList) {


System.out.print(i);
System.out.print(" ");
}
}

void sort(String array[]) {


if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}

void quickSort(int lowerIndex, int higherIndex) { int i =


lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];

while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) { i++;
}

while (this.names[j].compareToIgnoreCase(pivot) > 0) { j--;


}

if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}

void exchangeNames(int i, int j)


{ 42
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
KG REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

43
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Output:

15. Write a Java program that implements Bubble sort algorithm for sorting in descending
order and also shows the number of interchanges occurred for the given set of integers.

Source Code:

import java.util.Scanner;
public class BubbleSort {

public static void main(String[] args) { Scanner read = new


Scanner(System.in); int size, count = 0;
//Reading size of the list
System.out.print("Enter the list size: ");
size = read.nextInt();

//Creating list with elements


int list[] = new int[size];
System.out.println("Enter any " + size + " integer numbers: "); for(int i = 0; i <
size; i++)
list[i] = read.nextInt();

// Bubble sort logic


int temp=0;
for(int i=0;i<size-1;i++) { for(int j=0;j<size-i-
1;j++) {
Dept of CSE if(list[j]<lIiIsBt[.jT+e1c]h) I{I Sem 44
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
count++;
}
}
}

// Displaying sorted list


System.out.println("List of sorted elements: ");
for(int x:list) {
System.out.print(x + " ");
}
System.out.println("\nTotal number of Interchanges is " + count);
}
}

Output:

Dept of CSE II B.Tech II Sem 45


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Additional Programs

1. Write a java program that connects to a database using JDBC


Aim:To Write a java program that connects to a database using JDBC
Source Code:

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

2. Write a java program to connect to a database using JDBC and insert values into it
Aim: To Write a java program to connect to a database using JDBC and insert values into it
Source Code:
import java.sql.*;

// Main/App class of above Connection class


public class GFG {

// MAin driver method


public static void main(String[] args)
{
// Step 2: Showing above Connection class i.e
// loading and registering drivers

// Initially assigning NULL parameters


// to object of Connection class
Connection con = null;
PreparedStatement ps = null;

// Step 3: Establish the connection


con D=ecpotnonfeC
ctSio
En.connectDB(); II B.Tech II Sem 46
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

// Try block to check if exception/s occurs


try {

// Step 4: Create a statement


String sql = "insert into cuslogin values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)";

// Step 5: Execute the query


ps = con.prepareStatement(sql);

// Step 6: Process the results


ps.execute();
}

// Optional but recommended


// Step 7: Close the connection

// Catch block to handle the exception/s


catch (Exception e) {

// Print the exception


System.out.println(e);
}
}
}
Output:

3. Write a java program to connect to a database using JDBC and delete values from it
Aim: To Write a java program to connect to a database using JDBC and delete values from it
Source Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
im
D ptoortf jCaSvEa.sql.Statement;
ep II B.Tech II Sem 47
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:

ID: 100, Age: 30, First: Zara, Last: Ali


ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal

4. Write a java program for handling Mouse events

Aim: To Write a java program for handling Mouse events

Source Code:
import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MouseEvents" width=300 height=100>

</applet>
Dept of CSE II B.Tech II Sem 48
*/
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

// Handle mouse entered.

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates
Dept of CSE II B.Tech II Sem 49
mouseX = 0;
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

mouseY = 10;

msg = "Mouse exited.";

repaint();

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

// Handle button released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "*";

showStatus("Dragging mouse at " + mouseX + ", " + mouseY);


Dept of CSE II B.Tech II Sem 50
repaint();
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// show status

showStatus("Moving mouse at " + me.getX() + ", " + me.getY());

// Display msg in applet window at current X,Y location.

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

Output:

Dept of CSE II B.Tech II Sem 51

You might also like