Java Lab Manual - Pagenumber
Java Lab Manual - Pagenumber
EXPERIMENT - 1
1
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false
2
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
b = s.nextInt();
System.out.print("Enter c:");
c = s.nextInt();
D = b * b - 4 * a * c;
if(D > 0)
{
System.out.println("Roots are real and unequal");
r1 = ( - b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
System.out.println("First root is:"+r1);
System.out.println("Second root is:"+r2);
}
else if(D == 0)
{
System.out.println("Roots are real and equal");
r1 = (-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
}
else
{
System.out.println("Roots are imaginary");
}
}
}
OUT-PUT:
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:3
3
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
Enter c:1
Roots are real and unequal
First root is:-0.5
Second root is:-1.0
c) Bike Race
AIM: Five Bikers Compete in a race such that they drive at a constant speed which may or
may not be the same as the other. To qualify the race, the speed of a racer must be
more than the average speed of all 5 racers. Take as input the speed of each racer and
print back the speed of qualifying racers.
SOURCE-CODE:
import java.util.*;
class racedemo
{
public static void main(String[] args)
{
float s1,s2,s3,s4,s5,average;
Scanner s = new Scanner(System.in);
System.out.println("Enter speed of first racer:");
s1 = s.nextFloat();
System.out.println("Enter speed of second racer:");
s2 = s.nextFloat();
System.out.println("Enter speed of third racer:");
s3 = s.nextFloat();
System.out.println("Enter speed of fourth racer:");
s4 = s.nextFloat();
System.out.println("Enter speed of fifth racer:");
s5 = s.nextFloat();
4
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
average=(s1+s2+s3+s4+s5)/5;
if(s1>average)
System.out.println("First racer is qualify racer:");
else if(s2>average)
System.out.println("Second racer is qualify racer:");
else if(s3>average)
System.out.println("Third racer is qualify racer:");
else if(s4>average)
System.out.println("Fourth racer is qualify racer:");
else if(s5>average)
System.out.println("Fifth racer is qualify racer:");
}
}
OUT-PUT:
Enter speed of first racer:
4.5
Enter speed of second racer:
6.7
Enter speed of third racer:
3.8
Enter speed of fourth racer:
5.3
Enter speed of fifth racer:
4.9
Second racer is qualify racer:
d) A case study
AIM: A case study on public static void main(250 words)
5
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
Case study:
The SOURCE-CODE structure of a simple java SOURCE-CODE is given below with
different steps
Step-1: Click start+run and then type notepad in run dialog box and click OK. It displays
Notepad.
Step-2: In run dialogbox type cmd and click OK. It displays command prompt.
Step-3: Type the following SOURCE-CODE in the Notepad and save the SOURCE-CODE
as “example.java” in a current working directory.
class example
{
public static void main(String args[])
{
System.out.println(“Welcome”);
}
}
Step-4 (Compilation): To compile the program type the following in current working
directory and then click enter.
c:\xxxx >javac example.java
Step-5 (Execution): To run the program type the following in current working directory and
then click enter.
c:\xxxx>java example
Explanation:
Generally the file name and class name should be same. If it is not same then the java file
can be compiled but it cannot be executed. That is when execution it gives the
following error
Exception in thread "main" java.lang.NoClassDefFoundError: ex
In “public static void main(String args[])” statement
public is an access specifier. If a class is visible to all classes then public is used
6
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
main() must be declared as public since it must be called by outside of its class.
The keyword static allows main() to be called without creating object of the class.
The keyword void represents that main( ) does not return a value.
The main method contains one parameter String args[].
We can send some input values (arguments) at run time to the String args[] of the main
method . These arguments are called command line arguments. These command line
arguments are passed at the command prompt.
In System.out.println("Welcome"); statement
System is a predefined class that provides access to the system.
out is the OUT-PUT stream.
println() method display the OUT-PUT in different lines. If we use print() method it
display the OUT-PUT in the same line
EXPERIMENT - 2
7
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
8
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
Enter total number of elements:
5
Enter elements:
24689
Enter the search value:
8
number found
b) Bubble sort
AIM: To write a JAVA program to sort for an element in a given list of elements using
bubble sort
SOURCE-CODE:
import java.util.Scanner;
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
for(i=0;i<n;i++)
9
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("The sorted elements are:");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
}
}
OUT-PUT:
Enter total number of elements:
10
Enter elements:
3257689140
The sorted elements are:
0123456789
c) Merge sort:
AIM: To write a JAVA program to sort for an element in a given list of elements using
merge sort
SOURCE-CODE:
10
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
import java.util.*;
class mergedemo
{
public static void main(String args[])
{
int n1,n2,i,j,k;
int a[ ]=new int[20];
int b[ ]=new int[20];
int c[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter number of elements in first array:");
n1 = s.nextInt();
System.out.println("Enter sorted elements of first array:");
for (i = 0; i < n1; i++)
a[i] = s.nextInt();
System.out.println("Enter number of elements in second array:");
n2 = s.nextInt();
System.out.println("Enter sorted elements of second array:");
for (j = 0; j < n2; j++)
b[j] = s.nextInt();
i = 0;
j = 0;
k = 0;
while((i < n1) && (j <n2))
{
if(a[i] > b[j])
c[k++] = b[j++];
else
11
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
c[k++] = a[i++];
}
while(i < n1)
c[k++] = a[i++];
while(j < n2)
c[k++] = b[j++];
System.out.println("After merging the elements are:\n");
for(i = 0; i < (n1 + n2); i++)
System.out.print("\t"+c[i]);
}
}
OUT-PUT:
Enter number of elements in first array:
6
Enter elements of first array:
8 9 12 13 15 18
Enter number of elements in second array:
5
Enter elements of second array:
6 7 10 11 20
After merging the elements are:
6 7 8 9 10 11 12 13 15 18 20
d) Implementing StringBuffer
AIM: To write a JAVA program using StringBuffer to delete, remove character
SOURCE-CODE:
class stringbufferdemo
12
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
OUT-PUT:
World
Some Content
Hello World
EXPERIMENT - 3
13
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}
}
OUT-PUT:
10
20
14
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}
}
OUT-PUT:
10
20
15
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
}
OUT-PUT:
The area is:200
OUT-PUT:
The area is:200
b) Implementing Constructor
AIM: To write a JAVAto implement constructor
16
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
SOURCE-CODEs:
(i)A constructor with no parameters:
class A
{
int l,b;
A()
{
l=10;
b=20;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}
}
OUT-PUT:
The area is:200
17
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area();
System.out.println("The area is: "+r);
}
}
OUT-PUT:
The area is:200
EXPERIMENT - 4
a) Constructor Overloading
18
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
19
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
int r2=a2.area();
System.out.println("The area is: "+r2);
}
}
OUT-PUT:
The area is: 200
The area is: 1200
b) Method Overloading
AIM: To write a JAVA program implement method overloading
SOURCE-CODE:
class A
{
int l=10,b=20;
int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}
}
class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
20
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
int r1=a1.area();
System.out.println("The area is: "+r1);
int r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}
}
OUT-PUT:
The area is: 200
The area is: 100
EXPERIMENT - 5
21
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}
}
OUT-PUT:
Inside A's Constructor
Inside B's Constructor
22
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}
}
class multidemo
{
public static void main(String args[])
{
C c1=new C();
}
}
OUT-PUT:
Inside A's Constructor
Inside B's Constructor
Inside C's Constructor
c)Abstract Class
AIM: To write a java program for abstract class to find areas of different shapes
SOURCE-CODE:
abstract class shape
{
abstract double area();
}
class rectangle extends shape
23
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
double l=12.5,b=2.5;
double area()
{
return l*b;
}
}
class triangle extends shape
{
double b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}
}
class square extends shape
{
double s=6.5;
double area()
{
return 4*s;
}
}
class shapedemo
{
public static void main(String[] args)
{
rectangle r1=new rectangle();
24
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
The area of rectangle is: 31.25
The area of triangle is: 13.65
The area of square is: 26.0
EXPERIMENT - 6
25
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}
OUT-PUT:
The vol. is:6000
26
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
27
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
The vol. is:18000
b) Implementing interface
AIM: To write a JAVA program to implement Interface.
SOURCE-CODEs:
28
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}
}
OUT-PUT:
B's method
C's method
29
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
30
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
This is in display method
This is in show method
This is in callme method
This is in call method
31
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
This is in B's method
This is C's method
32
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}
}
class interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call();
}
}
OUT-PUT:
interface A
interface B
interface C
EXPERIMENT - 7
33
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
java.lang.ArithmeticException: / by zero
After the catch statement
34
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
java.lang.ArrayIndexOutOfBoundsException: 10
After the catch statement
35
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
EXPERIMENT – 8
a)Runtime Polymorphism
SOURCE-CODE:
AIM: To write a JAVA program that implements Runtime polymorphism
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
36
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
Inside C class
Inside B class
Inside A class
37
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Upcasting
38
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
EXPERIMENT –9
a)creation of illustrating throw
SOURCE-CODE:
AIM: To write a JAVA program for creation of Illustrating throw
class throwdemo
{
public static void main(String args[])
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
39
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
java.lang.NullPointerException: demo
OUT-PUT:
40
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
java.lang.ArithmeticException: / by zero
OUT-PUT:
2
This is inside finally block
41
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
java.lang.ArithmeticException: / by zero
(ii)NullPointer Exception
class nullpointerdemo
{
public static void main(String args[])
42
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
try
{
String a = null;
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NullPointerException
(iii)StringIndexOutOfBound Exception
class stringbounddemo
{
public static void main(String args[])
{
try
{
String a = "This is like chipping ";
char c = a.charAt(24);
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
43
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.StringIndexOutOfBoundsException:
String index out of range: 24
(iv)FileNotFound Exception
import java.io.*;
class filenotfounddemo
{
public static void main(String args[])
{
try
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified)
44
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
(v)NumberFormat Exception
class numberformatdemo
{
public static void main(String args[])
{
try
{
int num = Integer.parseInt ("akki") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NumberFormatException: For input string: "akki"
(vi)ArrayIndexOutOfBounds Exception
class arraybounddemo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];
a[6] = 9;
45
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (e);
}
}
}
OUT-PUT:
java.lang.ArrayIndexOutOfBoundsException: 6
46
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
System.out.println(e);
}
}
}
OUT-PUT:
A: demo
EXPERIMENT – 10
47
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C extends Thread
{
48
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
49
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
good morning
hello
good morning
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
welcome
hello
good morning
hello
welcome
hello
welcome
hello
hello
welcome
hello
welcome
50
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
welcome
welcome
welcome
51
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C implements Runnable
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
52
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
}
}
class runnabledemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
t2.start();
t3.start();
}
}
OUT-PUT:
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
53
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
welcome
hello
hello
welcome
hello
welcome
hello
hello
welcome
welcome
welcome
welcome
54
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
55
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class isalivedemo
{
public static void main(String args[])
{
A a1=new A();
56
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
B b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
try
{
a1.join();
b1.join();
c1.join();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
}
}
OUT-PUT:
true good morning
true hello
true welcome
good morning hello
57
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
58
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
class daemondemo
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A();
A a3=new A();
a1.setDaemon(true);
a1.start();
a2.start();
a3.start();
}
}
OUT-PUT:
daemon thread work
user thread work
user thread work
EXPERIMENT - 11
a)Producer-Consumer problem
AIM: Write a JAVA program Producer Consumer Problem
SOURCE-CODE:
class A
{
int n;
boolean b=false;
59
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
60
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
A a1;
Thread t1;
producer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class consumer implements Runnable
{
A a1;
Thread t1;
consumer(A a1)
61
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class interdemo
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}
OUT-PUT:
Put:1
Got:1
Put:2
Got:2
Put:3
62
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
63
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
A thread can use wait() method to pause and do nothing depending upon some condition.
For example, in the producer-consumer problem, producer thread should wait if the queue
is full and consumer thread should wait if the queue is empty.
If some thread is waiting for some condition to become true, we can use notify and
notifyAll methods to inform them that condition is now changed and they can wake
up.
Both notify() and notifyAll() method sends a notification but notify sends the notification
to only one of the waiting thread, no guarantee which thread will receive notification
and notifyAll() sends the notification to all threads.
Things to remember:
1. We can use wait() and notify() method to implement inter-thread communication in Java.
Not just one or two threads but multiple threads can communicate to each other by
using these methods.
2. Always call wait(), notify() and notifyAll() methods from synchronized method or
synchronized block otherwise JVM will throw IllegalMonitorStateException.
3. Always call wait and notify method from a loop and never from if() block, because loop
test waiting condition before and after sleeping and handles notification even if
waiting for the condition is not changed.
4. Always call wait in shared object e.g. shared queue in this example.
5. Prefer notifyAll() over notify() method due to reasons given in this article
EXPERIMENT – 12
64
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
{
public static void main(String[] args)
{
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++)
{
System.out.println(urls[i].getFile());
}
}
}
OUT-PUT:
E:/java%20work/
65
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
By default the java run time system uses the current working directory.
Normally to execute a java SOURCE-CODE in any directory we have to set the path by
as follows set path= c:\SOURCE-CODE Files\java\jdk1.5.0_10\bin;
Setting environmental variable in windows xp:
Step-1:
Select My computer on the desktop and right click the mouse and then select properties
It displays the following “System Properties” dialog.
Step-2:
In System Properties click Advanced and then click Environment Variables
It displays the following “Environment Variables” dialog.
Step-3:
In Environment Variables click New in System variables
It displays the following “New System Variable” dialog box.
Step-4:
Now type variable name as a path and then variable value as
c:\SOURCE-CODE Files\java\jdk1.5.0_10\bin;
Step-5:
Click OK
66
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
67
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
10
20
EXPERIMENT - 13
68
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
int w, h;
Image i;
Graphics g1;
public void init()
{
w = getSize().width; h = getSize().height;
i = createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white ); g1.fillRect( 0, 0, w, h ); g1.setColor( Color.red );
i = createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white ); g1.fillRect( 0, 0, w, h ); g1.setColor( Color.blue );
addMouseMotionListener( this );
}
public void mouseMoved( MouseEvent e ) { }
public void mouseDragged( MouseEvent me )
{
int x = me.getX(); int y = me.getY();
g1.fillOval(x-10,y-10,20,20);
repaint();
me.consume();
}
public void update( Graphics g )
{
g.drawImage( i, 0, 0, this );
}
public void paint( Graphics g )
{
69
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
update(g);
}
}
OUT-PUT:
70
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
71
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
while(true)
{
Calendar clndr=Calendar.getInstance();
h=clndr.get(Calendar.HOUR_OF_DAY);
if(h>12)h-=12;
m=clndr.get(Calendar.MINUTE); s=clndr.get(Calendar.SECOND);
SimpleDateFormat frmatter=new SimpleDateFormat("hh:mm:ss",
Locale.getDefault());
Date d=clndr.getTime(); str=frmatter.format(d);
if(b)
{
synchronized (this)
{
while(b)
{
wait();
}
}
}
repaint();
thr.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
72
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
73
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
74
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
g.setColor(Color.red); g.fillRect(10,80,200,30);
g.setColor(Color.orange); g.drawRoundRect(10,120,200,30,20,20);
g.setColor(Color.green); g.fillRoundRect(10,160,200,30,20,20);
g.setColor(Color.blue); g.drawOval(10,200,200,30);
g.setColor(Color.black); g.fillOval(10,240,40,40);
g.setColor(Color.yellow); g.drawArc(10,290,200,30,0,180);
g.setColor(Color.yellow); g.fillArc(10,330,200,30,0,180);
g.setColor(Color.pink); g.fillPolygon(x,y,n);
}
}
OUT-PUT:
EXPERIMENT - 14
75
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
Mouse.
SOURCE-CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code="mouseevent" width=450 height=300></applet>
public class mouseevent extends Applet
implements MouseListener, MouseMotionListener
{
String s1=" ";
int x,y;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=100;
y=100;
s1="Mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=100;
y=200;
s1="Mouse entered";
76
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
repaint();
}
public void mouseExited(MouseEvent me)
{
x=100;
y=300;
s1="Mouse exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
s1="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
s1="Mouse Realeased";
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
s1="Mouse Dragged";
77
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
repaint();
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
s1="Mouse Moved";
repaint();
}
public void paint(Graphics g)
{
g.drawString(s1,x,y);
}
}
OUT-PUT:
78
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
in a Applet.
SOURCE-CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code="keyevent" width=450 height=300></applet>
public class keyevent extends Applet implements KeyListener
{
String s1=" ";
int x,y;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
x=100;
y=200;
s1= "key pressed ";
repaint();
}
public void keyReleased(KeyEvent ke)
{
x=100;
y=400;
s1= "key Released ";
repaint();
79
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
public void keyTyped(KeyEvent ke)
{
s1=s1+ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(s1,x,y);
}
}
OUT-PUT:
EXPERIMENT - 15
80
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class calculator extends JPanel implements ActionListener
{
JTextField jt = new JTextField();
double d= 0;
String op = "=";
boolean b1 = true;
calculator()
{
setLayout(new BorderLayout());
jt.setEditable(false);
add(jt, "North");
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(4, 4));
String s1 = "789/456*123-0.=+";
for (int i = 0; i < s1.length(); i++)
{
JButton b = new JButton(s1.substring(i, i + 1));
jp.add(b);
b.addActionListener(this);
}
add(jp, "Center");
}
public void actionPerformed(ActionEvent ae)
{
String s1 = ae.getActionCommand();
81
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
82
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
}
}
private void calculate(double n)
{
if (op.equals("+"))
d += n;
else if (op.equals("-"))
d -= n;
else if (op.equals("*"))
d *= n;
else if (op.equals("/"))
d /= n;
else if (op.equals("="))
d = n;
jt.setText("" + d);
}
public static void main(String[] args)
{
JFrame jf = new JFrame();
jf.setTitle("calculator");
jf.setSize(300, 300);
Container c = jf.getContentPane();
c.add(new calculator());
jf.show();
}
}
OUT-PUT:
83
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
84
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
try
{
t1.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void paint(Graphics g)
{
Calendar cal = new GregorianCalendar();
String h = String.valueOf(cal.get(Calendar.HOUR));
String m = String.valueOf(cal.get(Calendar.MINUTE));
String s = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(h + ":" + m + ":" + s, 20, 30);
}
}
OUT-PUT:
85
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
EXPERIMENT – 16
86
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
dx = -dx;
X = r;
}
else if (X + r > w)
{
dx = -dx;
X = w - r;
}
if (Y - r < 0)
{
dy = -dy;
Y = r;
}
else if (Y + r > h)
{
dy = -dy;
Y = h - r;
}
repaint();
try
{
Thread.sleep(50);
}
catch (Exception e)
System.out.println(e);
}
}
}
87
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
};
thread.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval((int)(X-r), (int)(Y-r), (int)d, (int)d);
}
public static void main(String[] args)
{
JFrame jf = new JFrame("bouncing ball");
jf.setSize(300, 200);
jf.setContentPane(new bouncingball());
jf.setVisible(true);
}
}
OUT-PUT:
88
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
AIM: To write a JAVA program JTree as displaying a real tree upside down
SOURCE-CODE:
import javax.swing.*;
import javax.swing.tree.*;
class realtree
{
public static void main(String[] args)
{
JFrame jf = new JFrame();
DefaultMutableTreeNode d1 = new DefaultMutableTreeNode("Color", true);
DefaultMutableTreeNode d2 = new DefaultMutableTreeNode("Black");
DefaultMutableTreeNode d3 = new DefaultMutableTreeNode("Blue");
DefaultMutableTreeNode d4 = new DefaultMutableTreeNode("Navy Blue");
DefaultMutableTreeNode d5 = new DefaultMutableTreeNode("Dark Blue");
DefaultMutableTreeNode d6 = new DefaultMutableTreeNode("Green");
DefaultMutableTreeNode d7 = new DefaultMutableTreeNode("White");
d1.add(d2);
d1.add(d3);
d3.add(d4);
d3.add(d5);
d1.add(d6);
d1.add(d7);
JTree jt = new JTree(d1);
jf.add(jt);
jf.setSize(200,200);
jf.setVisible(true);
}
}
89
Downloaded by Narasimha Prasad ([email protected])
lOMoARcPSD|46450972
OUT-PUT:
90
Downloaded by Narasimha Prasad ([email protected])