[go: up one dir, main page]

0% encontró este documento útil (0 votos)
23 vistas50 páginas

Java Lab Manual: Experimentos y Programas

LIST OF PROGRAMS
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOC, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
23 vistas50 páginas

Java Lab Manual: Experimentos y Programas

LIST OF PROGRAMS
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOC, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 50

KOMMURI PRATAP REDDY INSTITUTE OF

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

DEPARTMENT OF COMPUTER SCINCE AND ENGINEERING


(DATA SCIENCE)

JAVA PROGRAMMING
LAB MANUAL

Regulation : R22
Academic Year : 2023-2024

II B. TECH II SEMESTER

COMPUTER SCIENCE AND ENGINEERING


(DATA SCIENCE)
Kommuri Pratap Reddy Institute of Technology
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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 inter thread communication.
13 Write a Java program to list all the files in a directory including the files present
in all its sub directories
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
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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

Import java.awt.*;
import java.awt.event.*;
Public class Calculator implements ActionListener
{
Int c,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;
TextField tf;
GridLayout g;
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("/");
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);
}
Public void actionPerformed(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)
{
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)
{
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);
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:-
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:-
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;
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

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.

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

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:-
Kommuri Pratap Reddy Institute of Technology Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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();
}
}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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


// 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)
{
// 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
Kommuri Pratap Reddy Institute of Technology Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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);
Kommuri Pratap Reddy Institute of Technology Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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");
}
}
}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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

}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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

public static void main(String[] args)


{ A a = new A();
}
}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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

public void mouseReleased(MouseEvent me)

{ 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);
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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 {

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:
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();
}
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:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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
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
in ascending Order.

Source Code:

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)
{
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}

Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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();
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

// Bubble sort logic


int temp=0;
for(int i=0;i<size-1;i++) { for(int j=0;j<size-i- 1;j++) {
I I B . T e c h I I Sem
if(list[j]<l i s t[ j + 1 ] ) {
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:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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.Driv
er");
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;
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

// Step 3: Establish the connection


con
// Try block to check if exception/s occurs
try {

// Step 4: Create a statement


String sql = "insert into cuslogin values('geeksforgeeks','gfg','geeks@email.com','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
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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;

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


Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

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

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
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

mouseX = 0;

mouseY = 10;

msg = "Mouse

entered."; repaint();

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates
mouseX = 0;

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.


Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX =

me.getX(); mouseY

= me.getY(); msg =

"*";

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


repaint();

// 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:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301

También podría gustarte