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

Java Package and Thread Implementation Guide

The document outlines the creation of various Java packages and classes, including sorting and searching functionalities, exception handling for insufficient funds, thread synchronization, and GUI event handling. It includes code snippets for implementing these features, such as a simple calculator GUI, mouse and key event handling, and client-server communication. The document serves as a comprehensive guide for Java programming concepts and their implementations.

Uploaded by

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

Java Package and Thread Implementation Guide

The document outlines the creation of various Java packages and classes, including sorting and searching functionalities, exception handling for insufficient funds, thread synchronization, and GUI event handling. It includes code snippets for implementing these features, such as a simple calculator GUI, mouse and key event handling, and client-server communication. The document serves as a comprehensive guide for Java programming concepts and their implementations.

Uploaded by

s.snehith098
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

6B) Define a package with name “sortapp” in which declare an interface

“SortInterface”
with method sort () whose return type and parameter type should be void and empty.
Define “subsortapp” as sub package of “sortapp” package in which define class
“SortImpI” implementing “SortInterface” in which sort() method should print a
message
Licareer sort is used.
Define a package “searchingapp” in which declare an interface “SearchInterface”
with
search () method whose return type and parameter list should be void and empty
respectively.
Define “searchingimpl” package in which define a “SearchImpI” class implementing
“SearchInterface” defined in “searchingapp” package in which define a search()
method
which should print a message licareer search is used.
Define a class ExecutePackageB with main method using the above packages (classes
and
interfaces).

/program1
package sortapp;
public interface SortInterface
{
void sort();
}
/program2
package [Link];
import sortapp.*;
public class SortImpI implements SortInterface
{
public void sort()
{
[Link]("Sort Interface....");
}
}
/program3
package searchingapp;
public interface SearchInterface
{
void search();
}
/program4
package searchingimpI;
import [Link];
import [Link];
import [Link];
import [Link];
class ExecutePackageB
{
public static void main(String[] Strng args[])
{
SortImpI sortI=new SortImpI();
SearchImpI searchI=new SearchImpI();
[Link]();
[Link]();
}
}
Output:
D:\GGG>javac -d . [Link]
D:\GGG>javac -d . [Link]
D:\GGG>javac -d . [Link]
D:\GGG>javac -d . [Link]
D:\GGG>java ExecutePackageB
Sort Interface....
Search Interface......
D:\GGG>

7). Modify the withdraw() method of Account class such that this method should
throw
“InsufficientFundException” if the account holder tries to withdraw an amount that
leads
to condition where current balance becomes less than minimal balance otherwise
allow the
account holder to withdraw and update balance accordingly.
java
Copy code
import [Link];
class InsufficientException extends Exception{
double balance;
public InsufficientException(String msg){
super(msg);
}
void withdraw(){
double balance = 25000.00;
[Link]("Current Balance: "+balance);
try{
[Link]("Enter withdraw amount: ");
Scanner in = new Scanner([Link]);
double wamount = [Link]();
if(wamount > balance)
throw new InsufficientException("Insufficient balance in
account.....");
else{
balance = balance - wamount;
[Link]("Transaction Successfully Completed..........");
[Link]("After transaction current balance: "+balance);
}
}
catch(InsufficientException e){
[Link]("Caught: "+[Link]());
}
}
}
class ExecuteAccount6{
public static void main(String arg[]){
InsufficientException inew = new InsufficientException("Insufficient
balance in account");
[Link]();
}
}

8. A) Define two threads such that one thread should print even numbers and another
thread should print odd numbers.
java
Copy code
public class EvenOddNumber {
int i = 1;

public synchronized void printNumber(String threadNm) throws


InterruptedException
{
if([Link]("t1"))
{
if(i%2 == 1)
{
[Link]([Link]().getName()+":"+i++);
notify();
}
else{
wait();
}
}
else if([Link]("t2"))
{
if(i%2 == 0)
{
[Link]([Link]().getName()+":"+i++);
notify();
}
else{
wait();
}
}
}

public static void main(String[] args){


final EvenOddNumber obj = new EvenOddNumber();
Thread t1 = new Thread(new Runnable(){
public void run() {
try{
while(obj.i <= 10){
[Link]([Link]().getName());
}
}
catch(InterruptedException e){
[Link]();
}
[Link]("done t1");
}
});

Thread t2 = new Thread(new Runnable(){


public void run() {
try{
while(obj.i <= 10){
[Link]([Link]().getName());
}
}
catch(InterruptedException e){
[Link]();
}
[Link]("done t2");
}
});
[Link]("t1");
[Link]("t2");
[Link]();
[Link]();
}
}
text
Copy code
Output:

D:\AWT>javac [Link]
D:\AWT>java EvenOddNumber
t1:1
t2:2
t1:3
t2:4
t1:5
t2:6
t1:7
t2:8
t1:9
t2:10
done t2
done t1
D:\AWT>

B) Write a program to implement thread synchronization concept.


java
Copy code
//example of java synchronized method
class Table{
synchronized void printTable(int n)
{ //synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}
catch(Exception e){
[Link](e);
}
}
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table(); // only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
text
Copy code
Output:

D:\AWT>javac [Link]
D:\AWT>java TestSynchronization2
100
5
200
10
300
15
400
20
500
25
D:\AWT>

C) Define two threads such that one thread should read a line of text from text
file and
another thread should write that line of text to another file. (Thread
communication
example).
java
Copy code
import [Link].*;
import [Link].*;
public class ThreadReadDemo
{
public static void main(String[] args)
{
Thread t1 = new Thread(new MultiThread(),"A");
Thread t2 = new Thread(new MultiThread(),"B");
[Link]();
[Link]();
}
}

class MultiThread implements Runnable


{
private static BufferedReader br = null;
private List<String> list;
static
{
try
{
br = new BufferedReader(new FileReader("D:/[Link]"),10);
}
catch(FileNotFoundException e)
{
[Link]();
}
}

public void run()


{
String line = null;
int count = 0;
while(true)
{
[Link] = new ArrayList<String>();
synchronized(br)
{
try
{
while((line = [Link]()) != null)
{
if(count < 15)
{
[Link](line);
count++;
}
else
{
[Link](line);
count = 0;
break;
}
}
}
catch (IOException e)
{
[Link]();
}
}
try
{
[Link](1);
display([Link]);
}
catch(InterruptedException e)
{
[Link]();
}
if(line == null)
break;
}
}

public void display(List<String> list)


{
for(String str : list)
{
[Link](str);
}
}
}

Output:

D:\AWT>javac [Link]
D:\AWT>java ThreadReadDemo
void main()
{
printf("hello");
}

9) Design the user screen as follows and handle the events appropriately.

Add Window
First Number
Second Number
Result
[ textfields ]

[ ADD ] [ SUB ]

import [Link].*;
import [Link].*;
import [Link].*;

class AddSub extends Frame implements ActionListener


{
Label l1,l2,l3;
TextField t1,t2,t3;
JButton b1,b2;
AddSub()
{
super("Addition of two numbers");
setLayout(null);
setSize(500,400);
setVisible(true);

l1 = new Label("Enter the first no:");


l2 = new Label("Enter the second no:");
l3 = new Label("Result:");

t1 = new TextField();
t2 = new TextField();
t3 = new TextField();

b1 = new JButton("ADD");
b2 = new JButton("SUB");

add(l1);
add(l2);
add(l3);
add(t1);
add(t2);
add(t3);
add(b1);
add(b2);

[Link](100,50,150,20);
[Link](100,80,150,20);
[Link](100,110,150,20);

[Link](240,50,150,20);
[Link](240,80,150,20);
[Link](240,110,150,20);

[Link](200,150,70,50);
[Link](300,150,70,50);

[Link](this);
[Link](this);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}

public void actionPerformed(ActionEvent ae)


{
float a,b,c;
if([Link]() == b1)
{
a = [Link]([Link]().trim());
b = [Link]([Link]().trim());
c = a + b;
[Link]([Link](c));
}
if([Link]() == b2)
{
a = [Link]([Link]().trim());
b = [Link]([Link]().trim());
c = a - b;
[Link]([Link](c));
}
}

public static void main(String s[])


{
AddSub ob = new AddSub();
}
}

Output:

D:\AWT>javac [Link]
D:\AWT>java Addsub

10) Write a Java program for handling mouse events and key events.
// demonstrate the mouse event handlers.
import [Link].*;
import [Link].*;
import [Link].*;

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

public class MouseEvents extends Applet implements MouseListener,


MouseMotionListener, MouseWheelListener{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init(){


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(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
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me){
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Down";
repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me){
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Up";
repaint();
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me){
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me){
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}

// Handle mouse wheel moved.


public void mouseWheelMoved(MouseWheelEvent me){
// show status
showStatus("Mouse Wheel Moving at " + [Link]() + ", " + [Link]());
}

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


public void paint(Graphics g){
[Link](msg, mouseX, mouseY);
}
}

Output:

D:\AWT>appletviewer [Link]

// demonstrate some virtual key codes.


import [Link].*;
import [Link].*;
import [Link].*;

/* <applet code="KeyEvents" width=300 height=100></applet> */

public class KeyEvents extends Applet implements KeyListener{


String msg = "";
int X = 10, Y = 20; // output coordinates

public void init(){


addKeyListener(this);
requestFocus(); // to receive key events
}

public void keyPressed(KeyEvent ke){


int key = [Link]();
msg = "Key Down";
switch(key){
case KeyEvent.VK_PAGE_DOWN:
msg += " PAGE DOWN";
break;
case KeyEvent.VK_UP:
msg += " UP ARROW";
break;
case KeyEvent.VK_DOWN:
msg += " DOWN ARROW";
break;
case KeyEvent.VK_LEFT:
msg += " LEFT ARROW";
break;
case KeyEvent.VK_RIGHT:
msg += " RIGHT ARROW";
break;
}
repaint();
}

public void keyReleased(KeyEvent ke){


msg = "Key Up";
repaint();
}

public void keyTyped(KeyEvent ke){


msg = msg + [Link]();
repaint();
}

public void paint(Graphics g){


[Link](msg, X, Y);
}
}

11) a) Write a program for handling window events.


import [Link].*;
import [Link].*;
class Myclass implements WindowListener
{
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e)
{
[Link](0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f = new MyFrame();
[Link]("My AWT Frame");
[Link](400,400);
[Link](true);
[Link](new Myclass());
}
}
Output:
D:\AWT>javac [Link]
D:\AWT>java MyFrame

b) Develop an applet that displays a simple message.


import [Link].*;
import [Link];
/* <applet code="SimpleApplet" width=300 height=50> </applet> */
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link] ("A Simple Applet",100, 100);
}
}
Output:
D:\AWT>javac [Link]
D:\AWT>appletviewer [Link]

12) Develop a client that sends data to the server and also develop a server that
sends
data to the client (two way communication)

import [Link].*;
import [Link].*;
class Client2
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",777);
DataOutputStream dos=new DataOutputStream([Link]());

InputStream obj=[Link]();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
BufferedReader kb=new BufferedReader(new
InputStreamReader([Link]));
String str,str1;
while(!(str=[Link]()).equals("exit"))
{
[Link](str+"\n");
str1=[Link]();
[Link](str1);
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}

import [Link].*;
import [Link].*;
class Server2
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=[Link]();
[Link]("Connection Established\n");
OutputStream obj=[Link]();
PrintStream ps=new PrintStream(obj);
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));
BufferedReader kb=new BufferedReader(new
InputStreamReader([Link]));
String str,str1;
while((str=[Link]())!=null)
{
[Link](str);
str1=[Link]();
[Link](str1);
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](0);
}
}

Output:
C:\12>javac [Link]
C:\12>java Server2
Connection Established
hi

C:\12>javac [Link]
C:\12>java Client2
hi

You might also like