[go: up one dir, main page]

0% found this document useful (0 votes)
17 views67 pages

Java Lab Manual VR20 Regulation

Uploaded by

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

Java Lab Manual VR20 Regulation

Uploaded by

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

JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

VIGNAN’S INSTITUTE OF INFORMATION TECHNOLOGY


(Beside VSEZ,Duvvada,Gajuwaka,VSKP-530049.A.P.)
DEPARTMENT OF IT
JAVA PROGRAMMING LAB MANUAL
II Year B.Tech II Sem

Exercise - 1 (Basics)
a). Write a JAVA program to display default value of all primitive data type of JAVA

b). Write a java program that display the roots of a quadratic equation ax2+bx=0.

Calculate thediscriminate D and basing on value of D, describe the nature of root.

c). 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.

d) Write a case study on public static void main(250 words)

Exercise - 2 (Operations, Expressions, Control-flow, Strings)

a). Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.
b). Write a JAVA program to sort for an element in a given list of elements using bubble sort
(c). Write a JAVA program to sort for an element in a given list of elements using merge sort.
(d) Write a JAVA program using StringBufferto delete, remove character.

Exercise - 3 (Class, Objects)


a). Write a JAVA program to implement class mechanism. – Create a class, methods and invoke
them inside main method.
b). Write a JAVA program to implement constructor.

Exercise - 4 (Methods)
a). Write a JAVA program to implement constructor overloading.
b). Write a JAVA program implement method overloading.

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

Page 1
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

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.

Exercise - 11 (Threads continuity)


a).Write a JAVA program Producer Consumer Problem
b).Write a case study on thread Synchronization after solving the above producer consumer
problem

Exercise – 12 (Packages)
a). Write a JAVA program illustrate class path
b). Write a case study on including in class path in your os environment of your package.
c). Write a JAVA program that import and use the defined your package in the previous
Problem

Page 2
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Exercise - 1 (Basics)

1.Write a JAVA program to display default value of all primitive data types of JAVA

AIM: JAVA program to display default value of all primitive data types of JAVA

DESCRIPTION:WRITE MINIMUM SIX LINES ABOUT THE PROGRAM

SOURCE CODE:
class DefaultValues
{
static byte b;
static short s;
staticinti;
static long l;
static float f;
static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
output

Page 3
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

2. Write a JAVA program that displays the roots of a quadratic equation ax2+bx+c=0.
Calculate the discriminent D and basing on the value of D, describe the nature of roots

import java.io.*;
import java.util.*;
class root
{
public static void main(String args[])
{
System.out.println("enter a b c values");
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();
int c=s.nextInt();
int d=((b*b)-(4*a*c));
if(d>0)
{
System.out.print("roots are real and distinct");
}
if(d==0)
{
System.out.print("roots are real");
}
if(d<0)
{
System.out.print("there is no solution");
}
}
}

Page 4
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Output

c). 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.

import java.util.Scanner;

class racer

int tot=0,avg;

int a[]=new int[5];

void get()

Page 5
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Scanner s=new Scanner(System.in);

for(int i=0;i<5;i++)

a[i]=s.nextInt();

void show()

for(int i=0;i<5;i++)

tot=tot+a[i];

avg=tot/5;

System.out.println("avg speed="+avg);

for(int i=0;i<5;i++)

if(a[i]>avg)

System.out.println(" "+(i+1)+". qualified speed="+a[i]);

class race

Page 6
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public static void main(String args[])

racer r=new racer();

r.get();

r.show();

Output

d) Write a case study on public static void main(250 words)

Public : is an Access Modifier, which defines who can access this Method. Public means that this
Method will be accessible by any Class(If other Classes are able to access this Class.).\

The first word in the statement, public, means that any object can use the main method. The first
word could also be static, but public static is the standard way. Still, public means that it is truly
the main method of the program and the means by which all other code will be used in the program.

Page 7
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Static : is a keyword which identifies the class related thing. This means the given Method or
variable is not instance related but Class related. It can be accessed without creating the instance
of a Class.

Even though you could write static public or public static, the program will work just fine. Still,
it's more common to use public static. In the context of Java, the static keyword means that the
main method is a class method. What this also means is that you can access this method without
having an instance of the class (Remember that the public keywords makes the method accessible
by all classes, so this makes it possible.)

Remember when we started at the beginning by calling this class the BoundingMain? In order to
get the main method to work within our BoundingMain class, we need the static keyword. The
main method can only be entered within an overarching class

Void : is used to define the Return Type of the Method. It defines what the method can return.
Void means the Method will not return any value.

main: is the name of the Method. This Method name is searched by JVM as a starting point for
an application with a particular signature only.

Exercise - 2 (Operations, Expressions, Control-flow, Strings)


a). Write a JAVA program to search for an element in a given list of elements using binary search
mechanism.

importjava.util.Scanner;
classBinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;

Page 8
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

while( first <= last )


{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
OUTPUT

b). Write a JAVA program to sort for an element in a given list of elements using bubble
sort

In bubble sort algorithm, array is traversed from first element to last element. Here, current
element is compared with the next element. If current element is greater than the next element, it is
swapped.

public class BubbleSortExample {


static void bubbleSort(int[] arr) {

Page 9
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");


for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");


for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}

}
}

Page 10
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

OUTPUT

(c). Write a JAVA program to sort for an element in a given list of elements using merge
sort.

Merge sort is a divide and conquer algorithm.

Page 11
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Steps to implement Merge Sort:

1) Divide the unsorted array into n partitions, each partition contains 1 element. Here the one
element is considered as sorted.
2) Repeatedly merge partitioned units to produce new sublists until there is only 1 sublist
remaining. This will be the sorted list at the end.

Conceptually, a merge sort works as follows :


i) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered
sorted).
ii) Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be
the sorted list.

import java.util.Scanner;
/* Class MergeSort */

Page 12
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public class MergeSortexample

/* Merge Sort function */

public static void sort(int[] a, int low, int high)

int N = high - low;

if (N <= 1)

return;

int mid = low + N/2;

// recursively sort

sort(a, low, mid);

sort(a, mid, high);

// merge two sorted subarrays

int[] temp = new int[N];

int i = low, j = mid;

for (int k = 0; k < N; k++)

if (i == mid)

temp[k] = a[j++];

else if (j == high)

Page 13
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

temp[k] = a[i++];

else if (a[j]<a[i])

temp[k] = a[j++];

else

temp[k] = a[i++];

for (int k = 0; k < N; k++)

a[low + k] = temp[k];

/* Main method */

public static void main(String[] args)

Scanner scan = new Scanner( System.in );

System.out.println("Merge Sort Test\n");

int n, i;

/* Accept number of elements */

System.out.println("Enter number of integer elements");

n = scan.nextInt();

/* Create array of n elements */

int arr[] = new int[ n ];

Page 14
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

/* Accept elements */

System.out.println("\nEnter "+ n +" integer elements");

for (i = 0; i < n; i++)

arr[i] = scan.nextInt();

/* Call method sort */

sort(arr, 0, n);

/* Print sorted Array */

System.out.println("\nElements after sorting ");

for (i = 0; i < n; i++)

System.out.print(arr[i]+" ");

System.out.println();

OUTPUT

Page 15
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

(d) Write a JAVA program using StringBufferto delete, remove character.


/*
Java StringBuffer delete remove character or clear content Example
This example shows how to delete or remove a particular character or clear
entire content of a StringBuffer object.
*/

public class JavaStringBufferDeleteExample {

public static void main(String[] args) {


/*
Java StringBuffer class following methods to delete / remove characters
or claring the contents of a StringBuffer object.
*/

/*
StringBuffer delete(int start, int end) remove the characters from start
index to an end-1 index provided.
This method can throw a StringIndexOutOfBoundException if the start
index is invalid.
*/
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);

Page 16
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

/*
To clear contents of a StringBuffer use delete(int start, int end) method
in the below given way
*/
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);

/*
StringBuffer deleteCharAt(int index) deletes the character at specified
index.
This method throws StringIndexOutOfBoundException if index is negative
or grater than or equal to the length.
*/
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}

OUTPUT

Page 17
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Exercise - 3 (Class, Objects)


a). Write a JAVA program to implement class mechanism. – Create a class, methods and
invoke them inside main method.

class student
{
int id=101;
String name="srinu";
String address="vizag";
int marks=100;

//methods
public void study()
{
System.out.println("student is studying");
}

public void read()


{
System.out.println("student is readung");
}
}
class student1
{
public static void main(String args[])
{

//creating object

student s=new student();


System.out.println("student id is"+s.id);
System.out.println("student name is"+s.name);

System.out.println("student address is"+s.address);


System.out.println("student marks is"+s.marks);

s.study();
s.read();

}
}

OUTPUT

Page 18
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

b). Write a JAVA program to implement constructor.


class rectangle
{
int length;
int breadth;
//default constructor
rectangle()
{
length=10;
breadth=5;
}

void area()
{
System.out.println("The area of rectangle is:"+(length*breadth));

}
}
class defaultconstruct
{
public static void main(String args[])
{

Page 19
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

//creating an object
rectangle obj=new rectangle();
obj.area();

}
}

OUTPUT

Exercise - 4 (Methods)
a). Write a JAVA program to implement constructor overloading.

class rectangle
{
int length;

Page 20
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

int breadth;
//default constructor
rectangle()
{
length=10;
breadth=5;
}

//parameterized constructor

rectangle(int l,int b)
{
length=l;
breadth=b;
}

//Normal method

void area()
{
System.out.println("The area of rectangle is:"+(length*breadth));

}
}

class Constructoroverload
{
public static void main(String args[])
{
//creating an object to call constructor
rectangle obj=new rectangle();
obj.area();

rectangle obj1=new rectangle(11,20);


obj1.area();

}
}
Output

Page 21
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

b). Write a JAVA program implement method overloading.

import java.lang.*;
import java.io.*;
class sample
{

//method to add two values


void add(inta,int b)
{
System.out.println("sum="+(a+b));
}

//method to add three values


void add(float a,floatb,float c )
{
System.out.println("Sum="+(a+b));
}
}

class overloading
{
public static void main(String args[])
{
//create sample class object

Page 22
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

sample s=new sample();


//call add() and pass two values
s.add(10,20);

//call add() and pass three values


s.add(10.5f,20.6f,7.4f);
}
}

Output

Page 23
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Exercise - 5 (Inheritance)

a). Write a JAVA program to implement Single Inheritance

class A
{
int a=5;
int b=3;
int c;

//superclass method
void add()
{
c=a+b;
System.out.println("sum of two values is:"+c);
}
}
class B extends A
{
//subclass method
void sub()
{
c=a-b;
System.out.println("substraction of two values is:"+c);
}
}
classsinglelevel
{
public static void main(String args[])
{

//creating object for subclass to access superclass members and subclass members
B obj=new B();
obj.add();
obj.sub();
}
}

Output

Page 24
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

b). Write a JAVA program to implement multi level Inheritance

class A
{

//normal method
void first()
{
System.out.println("this is class A");
}
}

class B extends A
{
//normal method
void second()
{
System.out.println("this is class B");
}
}

class C extends B
{
//normal method
void third()
{
}

Page 25
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

class multilevel
{
//main method
public static void main(String args[])
{
//creating object for subclass to access superclass members and subclass members
C obj=new C();
obj.first();
obj.second();
}
}

Output

Page 26
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

c). Write a java program for abstract class to find areas of different shapes

abstract class figure


{
intl,b;

//normal method or member function


……….
voidsetdata(intx,int y)
{
l=x;
b=y;
}

//abstract method
abstract void area();
}
class rectangle extends figure
{
void area()
{
System.out.println("area rect is:"+l*b);
}
}
classabdemo
{
public static void main(String args[])
{
rectangle r=new rectangle();

Page 27
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

r.setdata(10,20);
r.area();
}
}
Output

Exercise - 6 (Inheritance - Continued)

a). Write a JAVA program give example for “super” keyword.

class A
{
inti=25;
}
class B extends A
{
inti=27;
void display()
{
System.out.println("superclass i value is"+super.i);
System.out.println("sub class i value is"+i);
}
}
class superdemo1

Page 28
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

{
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}

Output

b). Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?

class student
{
//variables
intsno;
String sname;

//method
voidgetstudent(intx,String y)
{
sno=x;
sname=y;
}

voiddisplaystudent()
{

Page 29
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

System.out.println("student no="+sno+ "\n" +"student name="+sname);


}
}

interface test
{
voidgettest(intx,int y);
voiddisplaytest();
}

class result extends student implements test


{

//varibles
int m1,m2,total;

//methods
public void gettest(intx,int y)
{
m1=x;
m2=y;
}

public void displaytest()

System.out.println("m1="+m1 +"\n"+"m2="+m2);
}

voiddisplayresult()
{
total=m1+m2;
System.out.println("Total="+total);
}
}

class multiple
{
//mainmethod

public static void main(String args[])

Page 30
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

//creating an object for child class result

result r=new result();


r.getstudent(17,"satish");
r.gettest(70,80);
r.displaystudent();
r.displaytest();
r.displayresult();
}
}
Output

Exercise - 7 (Exception)
a).Write a JAVA program that describes exception handling mechanism

class ex1
{
public static void main(String args[])
{
try
{
//open the files
System.out.println("open files");
//do some processing
int n=args.length;

Page 31
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

System.out.println("n="+n);
int a=45/n;
System.out.println("a="+a);
}

catch(ArithmeticExceptionae)
{
//display the exception details
System.out.println(ae);

//display any message to the user


System.out.println("please pass data while running this program");
}

finally
{
//close the files
System.out.println("close files");
}
}
}
Output

b).Write a JAVA program Illustrating Multiple catch clauses


//handling multiple exceptions using try,catch and finally blocks

class multiplecatch

Page 32
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

{
public static void main(String args[])
{
try
{
//open the files
System.out.println("open files");

//do some processing


int n=args.length;
System.out.println("n="+n);
int a=45/n;
System.out.println("a="+a);

int b[]={10,20,30};
b[21]=100;
}

catch(ArithmeticException ae)
{

//display the exception details

System.out.println(ae);

//display any message to the usery


System.out.println("plaese pass data while running this program");

catch(ArrayIndexOutOfBoundsException aie)
{

//display exception details


aie.printStackTrace();

//display a message to user


System.out.println("plese see that the array index is with in the range");
}

finally
{

//close the files


System.out.println("close files");

}
}
}

Page 33
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Output

Exercise – 8 (Runtime Polymorphism)


a). Write a JAVA program that implements Runtime polymorphism
class A
{
void display()
{
System.out.println("class A");
}
}

class B extends A
{
//override display()

void display()
{
System.out.println("class B");
}
}

class C extends B
{
//override display()

void display()
{
System.out.println("class C");
}
}

class runtimepoly
{

Page 34
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public static void main(String args[])


{
A ref; //obtain reference of type A
A a= new A(); //object of type A
ref=a;
ref.display();

B b= new B(); //object of type B


ref=b;
ref.display();

C c= new C(); //object of type C


ref=c;
ref.display();
}
}
OUTPUT

b). Write a Case study on run time polymorphism, inheritance that implements in above
Problem.

Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic
method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.

• 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

Page 35
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

• 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.

It is a mechanism by which a call to an overriding method resolved at run time rather than
compile time. Java Executes over ridded methods based on the type of the object we referred.
Method overriding at runtime also known as Dynamic Method Dispatch.

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.

Exercise – 9 (User defined Exception)

a). Write a JAVA program for creation of Illustrating throw


class abc
{
void display()
{
System.out.println("hello");

}
}

Page 36
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

class throwdemo
{

public static void main(String args[])


{
abc a=null;

try
{
if(a==null)throw new NullPointerException();

else
a.display();
}

catch(NullPointerException e)
{

System.out.println("NullpointerException");
}
}
}

OUTPUT

Page 37
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

b). Write a JAVA program for creation of Illustrating finally

class Allocate {
public static void main(String[] args) {

try {
long data[] = new long[1000000000];
}
catch (Exception e) {
System.out.println(e);
}

finally {
System.out.println("finally block will execute always.");
}
}
}

OUTPUT

Page 38
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

c). Write a JAVA program for creation of Java Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.
Examples of Built-in Exception:

1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an


arithmetic operation.

// Java program to demonstrate


// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}

Page 39
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Output:

Can't divide a number by 0

2.ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed


with an illegal index. The index is either negative or greater than or equal to the size of the array.
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}

Output:

Array Index is Out Of Bounds

3. ClassNotFoundException : This Exception is raised when we try to access a class whose


definition is not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal {

} class Geeks {

} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}

Output:

ClassNotFoundException

Page 40
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

d).Write a JAVA program for creation of User Defined Exception

//to throw whenever balance amount is below Rs.1000

classMyException extends Exception


{
//store account information
staticintaccno[]={1001,1002,1003,1004,1005};
static String name[]={"srinu","vas","vinay","ravi","raju"};

static double bal[]={10000.00,12000.00,5600.50,999.00,1100.55};

//default constructor
MyException()
{
}

//parameterized constructor
MyException(String str)
{
super(str);
}

//main method
public static void main(String args[])
{
try
{
//display the heading for the table
System.out.println("ACCNO"+"\t"+"CUSTOMER"+"\t"+"BALANCE");

//display actual account information


for(inti=0;i<5;i++)
{
System.out.println(accno[i]+"\t"+name[i]+"\t"+bal[i]);

//display own exception if balance<1000


if(bal[i]<1000)
{
MyException me=new MyException("Balance amount is less");
throw me;
}
}//end of for

Page 41
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

} //end of try

catch(MyException me)
{
me.printStackTrace();
}
} //end of main
} //end of MyException class

Output:

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)

class A extends Thread


{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}

Page 42
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");

}
}

catch(Exception e)
{ }
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();

Page 43
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

C t3=new C();
t1.start();
t2.start();
t3.start();
}
}

OUTPUT

b). Write a program illustrating isAlive and join ()

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();

Page 44
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}

OUTPUT

b) public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();

Page 45
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}

t2.start();
}
}

OUTPUT

c). Write a Program illustrating Daemon Threads.


public class TestDaemonThread1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();

Page 46
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

TestDaemonThread1 t3=new TestDaemonThread1();

t1.setDaemon(true);//now t1 is daemon thread

t1.start();//starting threads
t2.start();
t3.start();
}
}

OUTPUT

Exercise - 11 (Threads continuity)


a).Write a JAVA program Producer Consumer Problem

//java program for producer and consumer--inter thread communication


class Thread1
{
int n;
boolean valueset=false;
synchronized int get()
{
if (!valueset)
try
{
wait();
}

Page 47
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
System.out.println("get" +n);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
valueset=false;
notify();
return n;
}
synchronized int put(int n)
{
if (valueset)
try
{
wait();
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
this.n=n;
valueset=true;
System.out.println("put"+n);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
notify();
return n;
}
}
class Producer implements Runnable

Page 48
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

{
Thread1 t;
Producer(Thread1 t)
{
this.t=t;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while (true)
{
t.put(i++);
}
}
}
class Consumer implements Runnable
{
Thread1 t;
Consumer(Thread1 t)
{
this.t=t;
new Thread(this,"Consumer").start();
}
public void run()
{
int i=0;
while (true)
{
t.get();
}
}
}
class ProducerConsumer
{
public static void main(String[] args)
{
Thread1 t=new Thread1();
new Producer(t);
new Consumer(t);
System.out.println("Press Control+c to exit");
}
}

Page 49
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

OUTPUT

b).Write a case study on thread Synchronization after solving the above producer
consumer problem

In computing, the producer–consumer problem (also known as the bounded-buffer problem) 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.

Implementation of Producer Consumer Class

• A LinkedList list – to store list of jobs in queue.

Page 50
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

• A Variable Capacity – to check for if the list is full or not


• A mechanism to control the insertion and extraction from this list so that we do not insert into
list if it is full or remove from it if it is empty.

Exercise – 12 (Packages)
a). Write a JAVA program illustrate class path

class path class path is an Environment variables that tells to the java compiler (javac) where to
Execute.

class setclasspath
{
public static void main(String args[])
{
System.out.println("set the class path to run java program");
}
}
OUTPUT

b). Write a case study on including in class path in your os environment of your package.

Page 51
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Class path

The CLASSPATH is an environment variable that tells the Java compiler javac.exe
where to look for class files to import or java.exe where to find class files to interpret.

In contrast, the PATH is an environment variable that tells the command processor the
where to look for executable files, e.g. *.exe, *.com and *.bat files. The Classpath is one
of the most confusing things in Java

os environment contains two packages main directory and subdirectory

c). Write a JAVA program that import and use the defined your package in the previous
Problem

Step1:create a sub directory for the main directory

C:\mypack\mypack

Step2

c:\xyz\mypack\edit base.java

Step3: Save and compile the program

Page 52
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

C:\xyz\mypack\javac base.java

Step4:

If we want to import the classes from subdirectory into main directory we


haveto remove subdirectory

C:\mypack\pack1\cd..and press enter key

C:\mypack

Step5

c:\mypack\edit packdemo.java

Step6

Save and compile the program

C:\xyz\javac packdemo.java

Page 53
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Step7

Execute the program

C:\xyz\java packdemo

output

base class is called

Exercise - 13 (Applet)

a).Write a JAVA program to paint like paint brush in applet.

/*<applet code="MouseDrag.class" width="300" height="300">

</applet>*/

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class MouseDrag extends Applet implements MouseMotionListener{

public void init(){

addMouseMotionListener(this);

setBackground(Color.red);

public void mouseDragged(MouseEvent me){

Page 54
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Graphics g=getGraphics();

g.setColor(Color.white);

g.fillOval(me.getX(),me.getY(),5,5);

public void mouseMoved(MouseEvent me) { }

OUTPUT:

Page 55
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

b. Write a JAVA program to display analog clock using Applet.

/*<applet code="MyClock.class" width="300" height="300">


</applet>*/

import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class MyClock extends Applet implements Runnable {

int width, height;


Thread t = null;

Page 56
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

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

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

Page 57
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

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
}
}
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 );

Page 58
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

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 );
}
}

OUTPUT:

Page 59
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

c). Write a JAVA program to create different shapes and fill colors using Applet.
/*<applet code="LinesRectsOvals.class" height="250" width="400"> </applet>*/

import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class LinesRectsOvals extends JApplet
{
public void paint(Graphics g)
{
//super.paint(g);
g.setColor(Color.red);
g.drawLine(5,30,350,30);
g.setColor(Color.blue);
g.drawRect(5,40,90,55);
g.fillRect(100,40,90,55);
g.setColor(Color.cyan);
//g.fillRoundRect(195,40,90,55);
//g.drawRoundRect(290,40,90,55);
g.setColor(Color.yellow);
//g.draw3DRect(5,100,90,55);

Page 60
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

//g.fill3DRect(100,100,90,55);
g.setColor(Color.magenta);
g.drawOval(195,100,90,55);
g.fillOval(290,100,90,55);
}
}

OUTPUT:

Page 61
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

/*
* to draw line in an applet window use,
* void drawLine(int x1,int y1, int x2, int y2)
* method.
*
* This method draws a line between (x1,y1) and (x2,y2)
* coordinates in a current color

Exercise - 14 (Event Handling)

a).Write a JAVA program that display the x and y position of the cursor movement using
Mouse.

import java.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/

public class MouseEvents extends Applet implements MouseListener, MouseMotionListener


{
String msg ;
int X,Y ;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
//returns the current xand y coordinate of the component origin
X = me.getX();
Y = me.getY();

msg = "Mouse clicked.";


repaint();
}

Page 62
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public void mouseEntered(MouseEvent me)


{

X = me.getX();
Y = me.getY();
msg = "Mouse entered.";
repaint();
}

public void mouseExited(MouseEvent me)


{
X = me.getX();
Y = me.getY();
msg = "Mouse exited.";
repaint();
}

public void mousePressed(MouseEvent me)


{
X = me.getX();
Y = me.getY();
repaint();
}

public void mouseReleased(MouseEvent me) {


X = me.getX();
Y = me.getY();
repaint();
}

public void mouseDragged(MouseEvent me) {


X = me.getX();
Y = me.getY();
msg = "mouse dragged";
repaint();
}
public void mouseMoved(MouseEvent me)
{
X = me.getX();
Y = me.getY();
msg = "mouseMotionmoved";
repaint();
}

Page 63
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public void paint(Graphics g)


{
g.drawString(msg, X, Y);
}
}
OUTPUT

b) Write a JAVA program that identifies key-up key-down event user entering text in a
Applet.

/*

<applet code="Key" width=300 height=400>

</applet>

*/

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Key extends Applet


implements KeyListener

Page 64
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}

Page 65
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

public void paint(Graphics g)


{
g.drawString(msg,X,Y);
}
}

OUTPUT:

Page 66
JAVA PROGRAMMING LAB MANUAL (VR20 Regulation)

Page 67

You might also like