0% found this document useful (0 votes)
86 views62 pages

Java Programming Lab: Submitted To: Submitted By: Ms. Savita Name: Roll No.: 00196407217 Group

Here are the key steps to solve the producer-consumer problem using threads in Java: 1. Define a fixed-size buffer (queue) to hold data. 2. Create Runnable producer and consumer classes that implement the producer and consumer logic. 3. The producer thread puts data in the buffer and the consumer thread removes data. 4. Synchronize access to the shared buffer using synchronization techniques like wait()/notify() to avoid race conditions. 5. The producer waits if the buffer is full and the consumer waits if the buffer is empty. 6. Notify the waiting thread after inserting/removing data so it can resume operation. 7. Create producer and consumer threads and start them

Uploaded by

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

Java Programming Lab: Submitted To: Submitted By: Ms. Savita Name: Roll No.: 00196407217 Group

Here are the key steps to solve the producer-consumer problem using threads in Java: 1. Define a fixed-size buffer (queue) to hold data. 2. Create Runnable producer and consumer classes that implement the producer and consumer logic. 3. The producer thread puts data in the buffer and the consumer thread removes data. 4. Synchronize access to the shared buffer using synchronization techniques like wait()/notify() to avoid race conditions. 5. The producer waits if the buffer is full and the consumer waits if the buffer is empty. 6. Notify the waiting thread after inserting/removing data so it can resume operation. 7. Create producer and consumer threads and start them

Uploaded by

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

Java Programming Lab

Submitted to: Submitted by:


Ms. Savita Name: Kumar Gourav
Roll No.: 00196407217
Group: 5-C-7

Maharaja Agrasen Institute of Technology, PSP Area, Sector – 22, Rohini, New Delhi – 110085
JAVA PROGRAMMING LAB

PRACTICAL RECORD

PAPER CODE : ETCS - 357

Name of the student : Kumar Gourav

University Roll No. : 00196407217

Branch : CSE

Section/ Group : 5-C-7

PRACTICAL DETAILS

a) Experiments according to the list provided by GGSIPU

Exp. no Experiment Name Date of Date of Remarks Marks


performance checking (10)

Kumar Gourav
00196407217
5-C-7
Exp. no Experiment Name Date of Date of Remarks Marks
performance checking (10)

Kumar Gourav
00196407217
5-C-7
Experiment A–1
Aim: Create a Java program to implement Stack and Queue concept.
Theory:
Stack:
A stack is a container of objects that are inserted and removed according to
the last-in first-out (LIFO) principle. In the push-down stacks only two
operations are allowed: push the item into the stack, and pop the item out
of the stack. A stack is a limited access data structure - elements can be
added and removed from the stack only at the top. push adds an item to the top
of the stack, pop removes the item from the top. A helpful analogy is to think of
a stack of books; you can remove only the top book, also you can add a new
book on the top. A stack is a recursive data structure. Here is a structural
definition of a Stack: a stack is either empty or it consists of a top and the rest
which is a stack.

Queue:
A queue is a container of objects (a linear collection) that are inserted and
removed according to the first-in first-out (FIFO) principle. An excellent
example of a queue is a line of students in the food court of the UC. New
additions to a line made to the back of the queue, while removal (or serving)
happens in the front. In the queue only two operations are allowed enqueue and
dequeue. Enqueue means to insert an item into the back of the queue, dequeue
means removing the front item. The picture demonstrates the FIFO access. The
difference between stacks and queues is in removing. In a stack we remove the
item the most recently added; in a queue, we remove the item the least recently
added.

Kumar Gourav
00196407217
5-C-7
Source Code:
(1) Stack Implementation:
import java.util.*;
class Test{
static void stack_push(Stack<Integer> stack)
{ for(int i = 0; i < 5; i++) { stack.push(i);

}
}
static void stack_pop(Stack<Integer> stack) {
System.out.println("Pop :"); for(int i = 0; i < 5; i++) {
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
static void stack_peek(Stack<Integer> stack) {
Integer element = (Integer) stack.peek(); System.out.println("Element on stack top : " +
element); }
static void stack_search(Stack<Integer> stack, int element)
{ Integer pos = (Integer) stack.search(element); if(pos ==
-1) System.out.println("Element not found"); else

System.out.println("Element is found at position " + pos);


}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);

Kumar Gourav
00196407217
5-C-7
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
System.out.println("Enter the element to be searched");
int i=sc.nextInt();
stack_search(stack, i);
}
}

(2) Queue Implementation:


import java.util.LinkedList;
import java.util.Queue;
class QueueExample {
public static void main(String[] args)
{
Queue<Integer> q = new LinkedList<>();
for (int i=0; i<5; i++)
q.add(i);
System.out.println("Elements of queue-"+q);
int removedele = q.remove();
System.out.println("removed element-" + removedele);
System.out.println(q);
int head = q.peek();
System.out.println("head of queue-" + head);
int size = q.size();
System.out.println("Size of queue-" + size);
}}

Kumar Gourav
00196407217
5-C-7
Output:

Stack Implementation

Queue Implementation

Kumar Gourav
00196407217
5-C-7
Experiment A–2

Aim: Write a Java package to show Dynamic Polymorphism and Interfaces.


Theory:

Runtime Polymorphism in Java :


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. In this process, an
overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable.

Interface:
Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then class must be declared abstract.
• A Java library example is, Comparator Interface. If a class implements this interface,
then it can be used to sort a collection.

Kumar Gourav
00196407217
5-C-7
Source Code:
(1) Dynamic Polymorphism:
import java.io.*;
class A {
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A {
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A {
void m1()
{
System.out.println("Inside C's m1 method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
A ref; ref = a; ref.m1(); ref = b; ref.m1(); ref = c; ref.m1();
}

Kumar Gourav
00196407217
5-C-7
}
(2) Interface:
import java.io.*;
interface in1 {
final int a = 10;
void display();
}
class testClass implements in1 {
public void display() {
System.out.println("method declared in interface");
}
public static void main (String[] args) {
testClass t = new testClass();
t.display();
System.out.println("Final value defined in interface"+a);
}
}

Kumar Gourav
00196407217
5-C-7
Output

Dynamic Polymorphism

Interface

Kumar Gourav
00196407217
5-C-7
Experiment A-3
Aim: Write a Java program to show multi-threaded Producer and Consumer Application.
Theory:

In computing, the producer–consumer problem (also known as the


boundedbufferproblem) is a classic example of a multi-process synchronization problem.
The problem describes two processes, the producer and the consumer, which share a
common, fixed-size buffer used as a queue.
• The producer’s job is to generate data, put it into the buffer, and start again.
• At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time.

Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the
producer, who starts to fill the buffer again. In the same way, the consumer can go to
sleep if it finds the buffer to be empty. The next time the producer
puts data into the buffer, it wakes up the sleeping consumer. An inadequate solution could
result in a deadlock where both processes are waiting to be awakened.

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException {
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.produce();
}
catch(InterruptedException e) {
e.printStackTrace();
}}
} );
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.consume();
}
catch(InterruptedException e) {
e.printStackTrace();
}}
});
t1.start();
t2.start();

Kumar Gourav
00196407217
5-C-7
t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>(); int capacity = 2;
public void produce() throws InterruptedException { int value =
0;
while (true) {
synchronized (this) {
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+ value);
list.add(value++);
notify();
Thread.sleep(1000);
}}
}
public void consume() throws InterruptedException { while (true)
{ synchronized (this) { while (list.size()==0) wait();
int val = list.removeFirst(); System.out.println("Consumer consumed-"
+ val);
notify();
Thread.sleep(1000);
}
}
}}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
Experiment A–4
Aim: Create a customized exception and also make use of all the 5 exception keywords.
Theory:
Java being an object oriented programming language, whenever an error
occurs while executing a statement, creates an exception object and then the
normal flow of the program halts and JRE tries to find someone that can
handle the raised exception. The exception object contains a lot of debugging
information such as method hierarchy, line number where the exception
occurred, type of exception etc. When the exception occurs in a method, the
process of creating the exception object and handing it over to runtime
environment is called “throwing the exception”.
Once runtime receives the exception object, it tries to find the handler for the
exception. Exception Handler is the block of code that can process the
exception object. The logic to find the exception handler is simple – starting
the search in the method where error occurred, if no appropriate handler
found, then move to the caller method and so on. So if methods call stack is
A->B->C and exception is raised in method C, then the search for appropriate
handler will move from C->B->A. If appropriate exception handler is found,
exception object is passed to the handler to process it. The handler is said to
be “catching the exception”. If there are no appropriate exception handler
found then program terminates printing information about the exception.
Note that Java Exception handling is a framework that is used to handle
runtime errors only, compile time errors are not handled by exception
handling in java.
We use specific keywords in java program to create an exception handle
block, we will look into these keywords next.
Java Exception Handling Keywords
java provides specific keywords for exception handling purposes, we will look
after them first and then we will write a simple program showing how to use
them for exception handling.
1. throw – We know that if any exception occurs, an exception object is
getting created and then Java runtime starts processing to handle them.
Sometime we might want to generate exception explicitly in our code,
for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw
exception to the runtime to handle it.
2. throws – When we are throwing any exception in a method and not
handling it, then we need to use throws keyword in method signature to
let caller program know the exceptions that might be thrown by the
method. The caller method might handle these exceptions or propagate
it toit’s caller method using throws keyword. We can provide multiple
exceptions in the throws clause and it can be used with main() method

Kumar Gourav
00196407217
5-C-7
also.
3. try-catch – We use try-catch block for exception handling in our code.
try is the start of the block and catch is at the end of try block to handle
the exceptions. We can have multiple catch blocks with a try and trycatch
block can be nested also. catch block requires a parameter that
should be of type Exception.
4. finally – finally block is optional and can be used only with try-catch
block. Since exception halts the process of execution, we might have
some resources open that will not get closed, so we can use finally
block. finally block gets executed always, whether exception occurred
or not.

Kumar Gourav
00196407217
5-C-7
Source Code:
public class ExceptionHandling {
static void throwMethod1() throws NullPointerException
{ System.out.println ("Inside throwMethod1");
throw new NullPointerException
("Throws_Demo1"); }
static void throwMethod2() throws ArithmeticException {
System.out.println("Inside throwsMethod2"); throw new
ArithmeticException("Throws_Demo2"); }
public static void main(String args[])
{
try {
throwMethod1();
}
catch (NullPointerException exp)
{
System.out.println ("Exception is: " +exp);
}
try
{
throwMethod2();
}
catch(ArithmeticException ae)
{
System.out.println("Exception is: "+ae);
}}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
Experiment A–5
Aim: Convert the content of a given file into the uppercase content of the same file.
Theory:
To convert/change lowercase string/character to uppercase string/character in Java
programming, you have to use ASCII value to convert the lowercase character into
uppercase character as shown in the following first program. And the second program,
uses the method toUpperCase() to convert lowercase string into uppercase string.

Convert Character from Lowercase to Uppercase:

To convert the lowercase character into uppercase character in Java


Programming, you have to ask to the user to enter the character, now start
converting lowercase character to uppercase character by using ASCII
values. To convert lowercase to uppercase, just minus 32 from the character
since the ASCII value of 'A' is 65 and the ASCII value of 'a' is 97, so 97-
65=32. So to convert character from lowercase to uppercase just minus 32
from the character.

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.io.*;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
public class TextFile {
public static void main (String[] args) throws IOException {
File file1 = new File("lowercase.txt"); File file2 = new
File("uppercase.txt");
BufferedReader in = (new BufferedReader(new
FileReader(file1))); PrintWriter out = (new PrintWriter(new
FileWriter(file2))); int ch;
while ((ch = in.read()) != -1) {
if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
}
out.write(ch);
}
in.close();
out.close();
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Lowercase

Uppercase

Kumar Gourav
00196407217
5-C-7
EXPERIMENT A-6
Aim: To develop an analog clock using Applet.
Theory:
Applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. Applet is embedded in a HTML page using the APPLET
or OBJECT tag and hosted on a web server.
Applets are used to make the web site more dynamic and entertaining.
1. All applets are sub-classes (either directly or indirectly) ofjava.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool called
applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class Clock extends Applet implements Runnable {
int width, height;
Thread t = null;
boolean threadSuspended;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void start() {
if ( t == null ) {
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();

Kumar Gourav
00196407217
5-C-7
}
}
}
}
public void stop() {
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance(); hours = cal.get( Calendar.HOUR_OF_DAY ); if (
hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() ); Date date =
cal.getTime();
timeString = formatter.format( date );
/ Now the thread checks to see if it should suspend itself
if ( threadSuspended ) {
synchronized( this ) { while
( threadSuspended )
{ wait();
}
}
}
repaint();
t.sleep( 1000 ); // interval specified in milliseconds
}

Kumar Gourav
00196407217
5-C-7
}
catch (Exception e) { }
}
void drawHand( double angle, int radius, Graphics g ) { angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
}
void drawWedge( double angle, int radius, Graphics g ) { angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y ); g.drawLine(
width/2+x3, height/2+y3, width/2 + x, height/2 + y ); g.drawLine( width/2+x2,
height/2+y2, width/2 + x3, height/2 + y3 );
}
public void paint( Graphics g ) {
g.setColor( Color.gray );
drawWedge( 2*Math.PI * hours / 12, width/5, g ); drawWedge( 2*Math.PI * minutes /
60, width/3, g ); drawHand( 2*Math.PI * seconds / 60, width/2, g );
g.setColor( Color.white );
g.drawString( timeString, 10, height-10 );
}
}

Kumar Gourav
00196407217
5-C-7
HTML File:
<html>
<body>
<applet code="MyClock.class" width="500" height="500">
</applet>
</body>
</html>

Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT A-7
Aim: Create a servlet that uses cookies to store the number of times a user has visited the
servlet.
Theory:

Servlets:
A Java servlet is a Java software component that extends the capabilities of a server.
Although servlets can respond to any types of requests, they most commonly implement
web containers for hosting web applications on web servers and thus qualify as a server-
side servlet web API. Such web servlets are the Java counterpart to other dynamic web
content technologies such as PHP and ASP.NET.
Three methods are central to the life cycle of a servlet. These are init(), service(), and
destroy(). They are implemented by every servlet and are invoked at specific times by the
server.
During initialization stage of the servlet life cycle, the web container initializes the servlet
instance by calling the init() method, passing an object implementing the
javax.servlet.ServletConfig interface. This configuration object allows the servlet to
access name-value initialization parameters from the web application.
After initialization, the servlet instance can service client requests. Each request is
serviced in its own separate thread. The web container calls the service() method of the
servlet for every request. The service() method determines the kind of request being made
and dispatches it to an appropriate method to handle the request. The developer of the
servlet must provide an implementation for these methods. If a request is made for a
method that is not implemented by the servlet, the method of the parent class is called,
typically resulting in an error being returned to the requester.
Finally, the web container calls the destroy() method that takes the servlet out of service.
The destroy() method, like init(), is called only once in the lifecycle of a servlet.

Kumar Gourav
00196407217
5-C-7
Source Code:
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCart extends HttpServlet
{
static int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("Welcome");
}
else
{
out.println("You visited "+i+" times");
}
i++;
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT A-8
Aim: Create a java bean having bound and constrained properties.
Theory:

A Java Bean is a java class that should follow following conventions:


o It should have a no-arg constructor.

o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Kumar Gourav
00196407217
5-C-7
Source Code:
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName(){return name;}
public static void main(String args[])
{
Employee e=new Employee();
e.setName("AKSHAY");
e.setId(007);
System.out.println(e.getName());

Kumar Gourav
00196407217
5-C-7
System.out.println(e.getId());
}
}
extends HttpServlet
{
static int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("Welcome");
}
else
{
out.println("You visited "+i+" times");
}
i++;
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-1
Aim: Write a program showing multi-level inheritance.
Theory:
Inheritance is the process of inheriting properties of objects of one class by objects of
another class. The class which inherits the properties of another class is called Derived or
Child or Sub class and the class whose properties are inherited is called Base or Parent or
Super class. When a class is derived from a class which is also derived from another
class, i.e. a class having more than one parent classes, such inheritance is called
Multilevel Inheritance.

Kumar Gourav
00196407217
5-C-7
Source Code:
class Living {
void Breathe() { System.out.println("All living beings breathe");}
}
class Animals extends Living {
void walk(){System.out.println("All animals can walk");}
}
class Human extends Animals{
void talk(){System.out.println("All humans can talk");}
}
class TestInheritance2
{
public static void main(String args[]){
Human h=new Human();
h.talk();
h.walk();
h.Breathe();
}
}
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-2
Aim: Write a program that implements method overriding.
Theory:
If a class inherits a method from its superclass, then there is a chance to override the
method provided that it is not marked final.
The benefit of overriding is: ability to define a behaviour that's specific to the subclass
type, which means a subclass can implement a parent class method based on its
requirement.
In object-oriented terms, overriding means to override the functionality of an existing
method.

Kumar Gourav
00196407217
5-C-7
Source Code:
class Parent
{
void method()
{
System.out.println("This is the parent class");
}
}
class Child extends Parent
{
void method()
{
System.out.println("This is the method of child class");
}
}
class Test1
{
public static void main(String args[])
{
Child c=new Child();
Parent p1=new Child();
Parent p=new Parent();
c.method();
p1.method();
p.method();
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-3
Aim: Write an application that shows thread synchronization.
Theory:

Multithreading:
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU. Each part of such program is called a thread.
So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms:


1. Extending the Thread class
2. Implementing the Runnable Interface

Kumar Gourav
00196407217
5-C-7
Source Code:
class Account
{
float balance=40000;
public float getBalance()
{
return balance;
}
}
class Withdrawal implements Runnable
{
Account obj;
Withdrawal(Account obj)
{
this.obj=obj;
}
public void run()
{
for(int i=1;i<=5;i++)
{
if(obj.getBalance()>0)
{makeWithdraw(10000);
}
else
System.out.println("\n\t NOt Enough balance for: " +Thread.currentThread().getName());
}
}
synchronized void makeWithdraw(int amt)

Kumar Gourav
00196407217
5-C-7
{if(obj.getBalance()>=amt)
{
System.out.println("\n\t"+
Thread.currentThread().getName()+"is going to withdraw"+": Current
sBalance= "+obj.getBalance());
try
{
Thread.sleep(2000);
obj.balance=obj.balance-amt;
System.out.println("\t Withdrawal done
for"+Thread.currentThread().getName()+" :Available Balance= "+obj.getBalance());
}
catch(Exception e)
{
System.out.println(e);
}
} }
}
class Sync
{
public static void main(String args[])
{
Account obj=new Account();
Withdrawal wob= new Withdrawal(obj);
Thread t1=new Thread(wob);
Thread t2=new Thread(wob);
t1.setName("CHEQUE");
t2.setName("DEBIT CARD");

Kumar Gourav
00196407217
5-C-7
t1.start();
t2.start();
while(t1.isAlive()||t2.isAlive())
{
try{
System.out.println("T1 state"+t1.getState());
Thread.sleep(2000);
System.out.println("T2 state"+t2.getState());
Thread.sleep(2000);
System.out.println("Current Thread Name"+Thread.currentThread().getName()+"\t
Thread state"+Thread.currentThread().getState());
}catch(Exception e)
{
e.printStackTrace();
}
}
}}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-4
Aim: Write an application that displays deadlock between threads.
Theory:

Deadlock describes a situation where two or more threads are blocked forever, waiting
for each other. Deadlock occurs when multiple threads need the same locks but obtain
them in different order. A Java multithreaded program may suffer from the deadlock
condition because the synchronized keyword causes the executing thread to block while
waiting for the lock, or monitor, associated with the specified object.

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.util.*;
class first
{
synchronized void mone(second ob)
{
for(int i=0;i<5;i++)
{
System.out.println("method one of first class run
by "+Thread.currentThread().getName());
//System.out.println(Thread.currentThread().getState()); try{
Thread.sleep(1000);
}
catch(Exception e){}
}
ob.mtwo();
}
synchronized void mtwo()
{
for(int i=0;i<5;i++)
{
System.out.println("method two of first class run
by "+Thread.currentThread().getName());
//System.out.println(Thread.currentThread().getState()); try{
Thread.sleep(1000);
}
catch(Exception e){}
}
}

Kumar Gourav
00196407217
5-C-7
}
class second
{
synchronized void mone(first ob)
{
for(int i=0;i<5;i++)
{
System.out.println("method one of second class run
by "+Thread.currentThread().getName());
//System.out.println(Thread.currentThread().getState()); try{
Thread.sleep(1000);
}
catch(Exception e){}
}
ob.mtwo();
}
synchronized void mtwo()
{
for(int i=0;i<5;i++)
{
System.out.println("method two of second class run
by "+Thread.currentThread().getName());
//System.out.println(Thread.currentThread().getState()); try{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}

Kumar Gourav
00196407217
5-C-7
class DeadLockConcept extends Thread {
first fi=new first();
second se=new second();
void abc()
{
this.start();
fi.mone(se);
}
public void run()
se.mone(fi);
}
public static void main(String args[])
{
DeadLockConcept d1= new DeadLockConcept(); d1.setName("Anant");
checkDLstate ch=new checkDLstate(Thread.currentThread(),d1);
ch.start();
d1.abc();
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-5
Aim: Write a basic file handling program in java with reader/writer.
Theory:

File handling –
File Handling in Java programming Language: FileWriter and FileReader classes are very
frequently used to write and read data from text files (they are Character Stream classes).
For any Byte stream classes, if you want to read and write them it is not wise and
recommended to use FileInputStream.
Java FileWriter is very useful in creating a file writing characters.This class inherits
from the OutputStream class.The constructors of the class FileWriter usually assume that
the byte-buffer size and default character encoding is acceptable.To declare them by
oneself we need to construct OutputStreamWriter on a FileOutputStream.It is meant for
writing streams of characters.
Java FileReader uses for reading the data which are in the form of characters and it is
done from a ‘text’ file.This class inherits from the InputStreamReaderClass.The
constructors of this class are assuming that the default character encoding and the default
byte- are appropriate. To confirm these values by your own, construct an
InputStreamReader on a FileInputStream.JavaFileReader uses for particularly reading
streams of character. For reading streams of raw bytes, FileInputStream can use.

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.io.*;
class Files
{
public static void main(String[ ] args) throws Exception
{
File f=new File("abc.txt");
FileWriter fw=new FileWriter(f,true);
PrintWriter pw=new PrintWriter(fw);
pw.println(102);
pw.println(23);
pw.println("good");
pw.println("file created");
pw.flush();
pw.close();
File f1=new File("abc.txt");
FileReader br=new FileReader(f1);
int ch=br.read();
while(ch!=-1)
{
System.out.print((char)ch);
ch=br.read();
}
br.close();
}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-6
Aim: Write an applet that displays a counter in the middle of applet.
Theory:
Applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. Applet is embedded in a HTML page using the APPLET
or OBJECT tag and hosted on a web server.
Applets are used to make the web site more dynamic and entertaining.
All applets are sub-classes (either directly or indirectly) of
java.applet.Appletclass.Applets are not stand-alone programs. Instead, they run within
either a web browser or an applet viewer. JDK provides a standard applet viewer tool
called applet viewer.
In general, execution of an applet does not begin at main() method.Output of an applet
window is not performed by System.out.println(). Rather it is handled with various AWT
methods, such as drawString().

Kumar Gourav
00196407217
5-C-7
Source Code:
package counter;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CounterApplet extends Applet implements ActionListener,
Runnable {
int counter;
Thread thread;
public void init() {
Button button = new Button("Start Number Count"); button.addActionListener(this);
add(button);
}
public void actionPerformed(ActionEvent ae) { counter = 0;
thread = new Thread(this);
thread.start();
}
public void run() {
try {
while (true) {
repaint();
Thread.sleep(1500);
++counter;
}

Kumar Gourav
00196407217
5-C-7
} catch (InterruptedException e) { e.printStackTrace();
}
}
public void paint(Graphics g) {
g.setFont(new Font("verdana", Font.BOLD, 30));
Dimension d = getSize();
int x = d.width / 2; int y =
d.height / 2; g.drawString("" +
counter, x, y);
}
}

Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-7
Aim: Write a program that displays life cycle of an applet.
Theory:

Life cycle of an applet:


1. init(): The applet's voyage starts here. In this method, the applet object is created
by the browser. Because this method is called before all the other methods,
programmer can utilize this method to instantiate objects, initialize variables,
setting background and foreground colors in GUI etc.; the place of a constructor in
an application. It is equivalent to born state of a thread.
2. start(): In init() method, even through applet object is created, it is
in inactive state. An inactive applet is not eligible for microprocessor time even
though the microprocessor is idle. To make the applet active, the init() method
calls start() method. In start() method, applet becomes active and thereby eligible
for processor time.
3. paint(): This method takes a java.awt.Graphics object as parameter. This class
includes many methods of drawing necessary to draw on the applet window. This
is the place where the programmer can write his code of what he expects from
applet like animation etc. This is equivalent to runnable state of thread.
4. stop(): In this method the applet becomes temporarily inactive. An applet can
come any number of times into this method in its life cycle and can go back to the
active state (paint() method) whenever would like. It is the best place to have
cleanup code. It is equivalent to the blocked state of the thread.
5. destroy(): This method is called just before an applet object is garbage collected.
This is the end of the life cycle of applet. It is the best place to have cleanup code.
It is equivalent to the dead state of the thread.

Kumar Gourav
00196407217
5-C-7
Source Code:
package counter;
import java.awt.*;
import java.applet.*;
public class CounterApplet extends Applet {
private static int initcall, startcall, paintcall, stopcall, destroycall;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
initcall=initcall+1;
}
public void start()
{
startcall=startcall+1;
}
public void paint(Graphics g)
{
paintcall=paintcall+1;
g.drawString("init Method is called for : "+initcall,0,14);
g.drawString("start Method is called for : "+startcall,0,30);
g.drawString("paint Method is called for : "+paintcall,0,46);
g.drawString("stop Method is called for : "+stopcall,0,62); g.drawString("destroy Method
is called for : "+destroycall,0,78); showStatus("Demo of Applet Life Cycle");
}
public void stop()
{
stopcall=stopcall+1;

Kumar Gourav
00196407217
5-C-7
}
public void destroy()
{
destroycall=destroycall+1;
}
}
import java.io.*;
class A {
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A {
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A {
void m1()
{
System.out.println("Inside C's m1 method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A();

Kumar Gourav
00196407217
5-C-7
B b = new B();
C c = new C();
A ref; ref = a; ref.m1(); ref = b; ref.m1(); ref = c; ref.m1();
}
}

Output:

Kumar Gourav
00196407217
5-C-7
EXPERIMENT B-8
Aim: Write a program to implement JDBC – ODBC Driver.
Theory:

Java Database Connectivity (JDBC) is an application programming interface (API) for


the programming language Java, which defines how a client may access a database. It is a
Java-based data access technology used for Java database connectivity. It is part of the
Java Standard Edition platform, from Oracle Corporation. It provides methods to query
and update data in a database, and is oriented towards relational databases. A JDBC-to-
ODBC bridge enables connections to any ODBC-accessible data source in the Java
virtual machine (JVM) host environment.

Kumar Gourav
00196407217
5-C-7
Source Code:
import java.sql.*;
class Anant
{
public static void main(String args[])
{
try{
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection con=
DriverManager.getConnection("jdbc:odbc:anant","system","anant");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from Employee");
while(rs.next())
{
String a,b,c,d;
a=rs.getString(1);
b=rs.getString(2);
c=rs.getString(3);
d=rs.getString(4);
System.out.println("\n\t"+a+" "+b+" "+c+" "+d);
}
rs.close();
st.close();
con.close();
}
catch(Exception ob){ob.printStackTrace();}
}

Kumar Gourav
00196407217
5-C-7
Output:

Kumar Gourav
00196407217
5-C-7

You might also like