Java Programming Lab Manual for JNTUK
Java Programming Lab Manual for JNTUK
INFORMATION TECHNOLOGY
(Applicable for batches admitted from 2019-2020)
Exercise - 5 (Inheritance)
a). Write a JAVA program to implement Single Inheritance
b). Write a JAVA program to implement multi level Inheritance
c). Write a java program for abstract class to find areas of different shapes
Exercise - 6 (Inheritance - Continued)
a). Write a JAVA program give example for “super” keyword.
b). Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
Exercise - 7 (Exception)
a).Write a JAVA program that describes exception handling mechanism b).Write a
JAVA program Illustrating Multiple catch clauses
Exercise – 8 (Runtime Polymorphism)
a). Write a JAVA program that implements Runtime polymorphism
b). Write a Case study on run time polymorphism, inheritance that implements in above
problem
Exercise – 9 (User defined Exception)
a). Write a JAVA program for creation of Illustrating throw b).
Write a JAVA program for creation of Illustrating finally
c). Write a JAVA program for creation of Java Built-in Exceptions
d).Write a JAVA program for creation of User Defined Exception
Exercise – 10 (Threads)
a). Write a JAVA program that creates threads by extending Thread class .First thread display “Good
Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display
“Welcome” every 3 seconds ,(Repeat the same by implementing Runnable) b). Write a program
illustrating isAlive and join ()
c). Write a Program illustrating Daemon Threads.
JAVA PROGRAMMING LAB
Cycle-II Programs
Exercise - 11 (Threads continuity)
Exercise - 13 (Applet)
i
a)Producer-Consumer problem 39
b)Case study on thread synchronization 41
12 Exercise – 12 (Packages) 42-45
a) Illustration of class path 42
b) A case study on including in class path in os environment 43
c) Creating and importing a package 45
13 Exercise - 13 (Applet) 46-49
a) Paint like Paint Brush in Applet 46
b) Display Analog Clock using Applet 47
c) Display Analog Clock using Applet 49
14 Exercise - 14 (Event Handling) 50-52
a) Cursor movement using mouse 50
b) Key-up and Key-down event 52
ii
II [Link] II Sem IT Java Lab Manual (R20)
Exercise - 1 (Basics)
a) Displaying default value of all primitive data types
Aim: To write a JAVA program to display default value of all primitive data type of JAVA
Program:
class defaultdemo
{
static byte b;
static short s;
static int i; static
long l; static
float f; static
double d; static
char c;
static boolean bl;
public static void main(String[] args)
{
[Link]("The default values of primitive data types are:"); [Link]("Byte
:"+b);
[Link]("Short :"+s);
[Link]("Int :"+i);
[Link]("Long :"+l);
[Link]("Float :"+f);
[Link]("Double :"+d);
[Link]("Char :"+c);
[Link]("Boolean :"+bl);
}
}
Output:
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
Aim: To write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the
discriminate D and basing on value of D, describe the nature of root.
Program:
import [Link].*;
class quadraticdemo
{
public static void main(String[] args)
{
int a, b, c; double
r1, r2, D;
Scanner s = new Scanner([Link]); [Link]("Given
quadratic equation:ax^2 + bx + c"); [Link]("Enter a:");
a = [Link]();
[Link]("Enter b:"); b
= [Link]();
[Link]("Enter c:"); c
= [Link]();
D = b * b - 4 * a * c;
if(D > 0)
{
[Link]("Roots are real and unequal"); r1
= ( - b + [Link](D))/(2*a);
r2 = (-b - [Link](D))/(2*a);
[Link]("First root is:"+r1);
[Link]("Second root is:"+r2);
}
else if(D == 0)
{
[Link]("Roots are real and equal"); r1
= (-b+[Link](D))/(2*a);
[Link]("Root:"+r1);
}
else
{
[Link]("Roots are imaginary");
}
}
}
Output:
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:3
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.
Program:
import [Link].*;
class racedemo
{
public static void main(String[] args)
{
float s1,s2,s3,s4,s5,average;
Scanner s = new Scanner([Link]);
[Link]("Enter speed of first racer:"); s1
= [Link]();
[Link]("Enter speed of second racer:"); s2 =
[Link]();
[Link]("Enter speed of third racer:"); s3
= [Link]();
[Link]("Enter speed of fourth racer:"); s4
= [Link]();
[Link]("Enter speed of fifth racer:"); s5
= [Link](); average=(s1+s2+s3+s4+s5)/ 5;
if(s1>average)
[Link]("First racer is qualify racer:");
else if(s2>average)
[Link]("Second racer is qualify racer:"); else
if(s3>average)
[Link]("Third racer is qualify
racer:"); else if(s4>average)
[Link]("Fourth racer is qualify racer:");
else if(s5>average)
[Link]("Fifth racer is qualify racer:");
}
}
Output:
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:
Program:
import [Link];
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;
int a[ ]=new int[20];
Scanner s = new Scanner([Link]);
[Link]("Enter total number of elements:"); n =
[Link]();
[Link]("Enter elements in sorted order:"); for
(i = 0; i < n; i++)
a[i] = [Link]();
[Link]("Enter the search value:");
num = [Link]();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
[Link]("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
[Link]( " Number is not found");
}
}
Output:
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
Program:
import [Link];
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner([Link]);
[Link]("Enter total number of elements:"); n =
[Link]();
[Link]("Enter elements:");
for (i = 0; i < n; i++)
a[i] = [Link]();
for(i=0;i<n;i++)
{
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;
}
}
}
[Link]("The sorted elements are:"); for(i=0;i<n;i+
+)
[Link]("\t"+a[i]);
}
}
Output:
Enter total number of elements:
10
Enter elements:
3257689140
The sorted elements are:
0 1 2 3 4 5 6 7 8 9
d) Implementing StringBuffer
Aim: To write a JAVA program using StringBuffer to delete, remove character
Program:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
[Link](0,6);
[Link](sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
[Link](sb2);
[Link](0, [Link]());
[Link](sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
[Link](0);
[Link](sb3);
}
}
Output:
World
Some Content
ello World
}
}
Output:
The area is:200
(ii) A constructor with parameters
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=[Link](); [Link]("The
area is: "+r);
}
}
Output:The area is:200
Program:
class A
{
int l,b;
A()
{
l=10;
b=20;
}
A(int u,int v)
{
l=u;
b=v;
}
int area()
{
return l*b;
}
}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A();
int r1=[Link]();
[Link]("The area is: "+r1); A
a2=new A(30,40);
int r2=[Link](); [Link]("The
area is: "+r2);
}
}
Output:
The area is: 200
The area is: 1200
b) Method
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();
int r1=[Link]();
[Link]("The area is: "+r1); int
r2=[Link](5,20);
[Link]("The area is: "+r2);
}
}
Output:
The area is: 200
The area is: 100
Exercise - 5 (Inheritance)
a) Implementing Single Inheritance
Program:
class A
{
A()
{
[Link]("Inside A's Constructor");
}
}
class B extends A
{
B()
{
[Link]("Inside B's Constructor");
}
}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}
}
Output:
Inside A's Constructor
Inside B's Constructor
Program:
class A
{
A()
{
[Link]("Inside A's Constructor");
}
}
class B extends A
{
B()
{
[Link]("Inside B's Constructor");
}
}
class C extends B
{
C()
{
[Link]("Inside C's Constructor");
}
}
class multidemo
{
public static void main(String args[])
{
C c1=new C();
}
}
Output:
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
Program:
Output:
The area of rectangle is: 31.25
The area of triangle is: 13.65 The
area of square is: 26.0
Programs:
(i) Using super to call super class constructor (Without parameters)
class A
{
int l,b;
A()
{
l=10;
b=20;
}
}
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=[Link]();
[Link]("The vol. is: "+r);
}
}
Output:
The vol. is:6000
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=[Link]();
[Link]("The vol. is: "+r);
}
}
Output:
The vol. is:18000
Output:
B's method
C's method
Exercise - 7 (Exception)
a) Exception handling mechanism
Aim: To write a JAVA program that describes exception handling mechanism
Program:
Usage of Exception Handling:
class trydemo
{
public static void main(String args[])
{
tr
y
{ int a=10,b=0;
int c=a/b;
[Link](c);
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("After the catch statement");
}
}
Output:
[Link]: / by zero
After the catch statement
multitrydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1}; [Link](d[10]);
[Link](c);
}
catch(ArithmeticException e)
{
[Link](e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("After the catch statement");
}
}
Output:
[Link]: 10
After the catch statement
Program:
class A
{
void display()
{
[Link]("Inside A class");
}
}
class B extends A
{
void display()
{
[Link]("Inside B class");
}
}
class C extends A
{
void display()
{
[Link]("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
[Link]();
ref=b1;
[Link]();
ref=a1;
[Link]();
}
}
Output:
Inside C class
Inside B class
Inside A class
▪ When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is made at run time.
▪ 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 SuperClass
obj=new SubClass
SuperClass
extends
SubClass
Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of
objects are referred to through a superclass reference variable, different versions of the method are executed.
Here is an example that illustrates dynamic method dispatch:
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may
differ according to banks. For example, SBI, ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of
interest
Bank
getRateOfInterest():float
extends
Program:
throwdemo
{
public static void main(String args[])
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
[Link](e);
}
}
}
Output:
[Link]: demo
}
}
}
Output:
[Link]: / by zero
This is inside finally block
Program(ii):
class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
[Link](c);
}
catch(ArithmeticException e)
{
[Link](e);
}
finall
y
{ [Link]("This is inside finally block");
}
}
}
Output:2This is inside finally block
Programs:
Output:
[Link]: / by zero
(ii)NullPointer Exception
class nullpointerdemo
{
public static void main(String args[])
{
try
{ String a = null; [Link]([Link](0));
(iii)StringIndexOutOfBound Exception
class stringbounddemo
{
public static void main(String args[])
{
try
{
String a = "This is like chipping ";
char c = [Link](24);
[Link](c);
}
catch(StringIndexOutOfBoundsException e)
{
[Link](e);
}
}
}
Output:
[Link]: String index out of range: 24
(iv)FileNotFound Exception
import [Link].*;
class filenotfounddemo
{
public static void main(String args[])
{
try
{
File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
[Link](e);
}
}
}
Output:
[Link]: E:\[Link] (The system cannot find the file specified)
(v)NumberFormat Exception
class numberformatdemo
{
Mr [Link] Rao Assistant professor
II [Link] II Sem IT Java Lab Manual (R20)
public static void main(String args[])
{
tr
y
{ int num = [Link] ("akki") ;
[Link](num);
}
catch(NumberFormatException e)
{
[Link](e);
}
}
}
Output:
[Link]: For input string: "akki"
(vi)ArrayIndexOutOfBounds Exception
class arraybounddemo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];
a[6] = 9;
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link] (e);
}
}
}
Output:
[Link]: 6
Output:
A: demo
Exercise – 10
(Threads) a) Extending
Thread class
Aim: To write a JAVA program that creates threads by extending Thread class .First thread display “Good
Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome”
every 3 seconds ,(Repeat the same by implementing Runnable)
Programs:
(i) Creating multiple threads using Thread class
class A extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000); [Link]("good
morning");
}
}
catch(Exception e)
{
[Link](e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000); [Link]("hello");
}
}
catch(Exception e)
{
[Link](e);
}
}
}
class C extends Thread
{
public void run()
{
try
Output:
good morning
good morning
hello
good morning
welcome good
morning hello
good morning
good morning
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
Program:
Program:
A
a2=new A();
A a3=new
A();
[Link](true);
[Link]();
[Link]();
[Link]();
}
}
Output:
daemon thread work
user thread work user
thread work
}
catch(Exception e)
{
[Link](e);
}
[Link]("Got:"+n);
b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b)
try
{
wait();
}
❖ We can use wait, notify and notifyAll methods to communicate between threads in Java.
❖ For example, if we have two threads running in your program [Link] and Consumer then producer
thread can communicate to the consumer that it can start consuming now because there are items to consume
in the queue.
❖ Similarly, a consumer thread can tell the producer that it can also start putting items now because there is
some space in the queue, which is created as a result of consumption.
❖ 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
Exercise – 12 (Packages)
a) Illustration of class path
Aim: To write a JAVA program illustrate class path
import [Link];
import [Link];
public class App
{
public static void main(String[] args)
{
ClassLoader sysClassLoader = [Link](); URL[]
urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< [Link]; i++)
{
[Link](urls[i].getFile());
}
}
}
Output:
E:/java%20work/
Aim: To write a case study on including in class path in your os environment of your package.
Environment Variables
OK Cancel
Step-2:
➢ In System Properties click Advanced and then click Environment Variables.
➢ It displays the following “Environment Variables” dialog.
Environment Variables
System Variables
New
OK Cancel
Step-3:
➢ In Environment Variables click New in System variables.
➢ It displays the following “New System Variable” dialog box.
OK Cancel
Step-4:
➢ Now type variable name as a path and then variable value as c:\
Program Files\java\jdk1.5.0_10\bin;
New System Variable
c:\Program Files\java\jdk1.5.0_10\bin;
OK Cancel
Step-5:
➢ Click OK
Output:
10
20
Program:
import [Link].*;
import [Link].*;
//<applet code="graphicsdemo" width="400" height="400"></applet>
public class graphicsdemo extends Applet
{
public void paint(Graphics g)
{
int x[]={10,220,220};
int y[]={400,400,520};
int n=3;
[Link](10,30,200,30);
[Link]([Link]); [Link](10,40,200,30);
[Link]([Link]); [Link](10,80,200,30);
[Link]([Link]); [Link](10,120,200,30,20,20);
[Link]([Link]); [Link](10,160,200,30,20,20);
[Link]([Link]); [Link](10,200,200,30);
[Link]([Link]); [Link](10,240,40,40);
[Link]([Link]); [Link](10,290,200,30,0,180);
[Link]([Link]); [Link](10,330,200,30,0,180);
[Link]([Link]); [Link](x,y,n);
}
}
Output:
Output:
Constructor overloading in Java allows you to have multiple constructors with different parameter lists within the same class, enabling objects to be initialized in different ways. For example, one constructor may take no arguments, while another may take several parameters, thus providing flexibility in object creation. The purpose is to provide different options for instantiating an object, tailoring it to the specific needs of different situations .
Java's StringBuffer provides a mutable sequence of characters and is more efficient for string manipulation compared to the immutable String class, as it allows changes without creating new objects. StringBuffer supports various operations like append, insert, and reverse, which can modify the contents efficiently. Unlike String, modifications to StringBuffer do not result in new instances, improving performance in scenarios involving numerous modifications within loops .
In the Producer-Consumer problem, the main challenges include race conditions, data inconsistency, and deadlocks when accessing shared resources. Java's synchronization mechanisms, such as synchronized blocks or methods, help serialize access to shared data, ensuring that only one thread can access critical sections at a time. This prevents race conditions and ensures consistency of the shared data. It also aids in blocking producer threads when the queue is full and consumer threads when the queue is empty .
The 'finally' block in Java exception handling provides a mechanism to execute important code such as cleanup operations, regardless of whether an exception is thrown or handled in the try-catch block. This is crucial for resource management, such as closing files or releasing network connections, ensuring that these operations take place to maintain resource integrity and prevent resource leaks .
Java interfaces support a form of multiple inheritance by allowing a class to implement multiple interfaces, thus inheriting the abstract methods of all interfaces. This provides a way to achieve multiple inheritance without the complexities and issues associated with it in languages that support traditional class-based multiple inheritance. Benefits include increased flexibility in design and the ability to specify what an object can do without defining how it does it, thus promoting loose coupling and high cohesion .
Creating packages in Java involves organizing classes and interfaces into namespaces using the 'package' keyword, which helps structure code logically and avoid naming conflicts. Using packages allows for more manageable codebases, scope management, and access control through visibility modifiers, enhancing encapsulation. Packages provide reusability and help developers manage large applications efficiently by grouping related classes and interfaces .
In Java, the 'super' keyword is used to refer to the immediate parent class of an object. It is typically used in the context of inheritance to call parent class constructors, methods, and to access the parent class's fields or properties. The 'super' keyword ensures that the correct method or constructor is called in hierarchical inheritances, especially when overridden methods are used in subclasses .
Runtime polymorphism in Java, achieved through method overriding, allows a method to perform different behaviors depending on the object that invokes the method. It is resolved during runtime as opposed to compile-time polymorphism, which is resolved during compilation. This mechanism uses dynamic method dispatch where the call to an overridden method is resolved at runtime. In contrast, compile-time polymorphism applies to method overloading and is resolved at the time of compilation .
Method overloading in Java allows multiple methods in the same class to have the same name with different parameter lists, which improves code readability and organization. It is a compile-time polymorphism feature that provides flexibility and a clear method structure without complicating class interfaces. However, overloading can lead to ambiguities if not used wisely, especially with type promotion, and it does not support return type-based differentiation .
In Java, checked exceptions are exceptions that must be either caught or declared in the method signature using a throws clause, representing anticipated but recoverable errors like IOException. Unchecked exceptions, derived from RuntimeException, indicate programming errors such as logic mistakes (e.g., NullPointerException) and do not require explicit handling. Managing checked exceptions involves robust error checking and reporting, while unchecked exceptions are often left to crash the program or handled using application-level logging .