0% found this document useful (0 votes)
165 views180 pages

20jg5a0503 (14exercises and Extra Programs)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 180

|| CSE R19 JAVA PROGRAMMING

EXERCISE:1(a)
Write a JAVA program to display default value of all primitive data type of
JAVA
AIM:
Java program to display default value of all primitive data type of JAVA
SOURCE CODE:
class Defaultvalue_of_datatypes
{
static byte a;
static short s;
static float f;
static int i;
static char c;
static double d;
static boolean b;
public static void main(String args[])
{
System.out.println("Datatype value of byte:"+a);
System.out.println("Datatype value of short:"+s);
System.out.println("Datatype value of float:"+f);
System.out.println("Datatype value of int:"+i);
System.out.println("Datatype value of char:' '"+c);
System.out.println("Datatype value of double:"+d);

System.out.println("Datatype value of boolen:"+b);


}
}

20JG5A0503 1|Page
|| CSE R19 JAVA PROGRAMMING

EXERCISE:1(b)

20JG5A0503 2|Page
|| CSE R19 JAVA PROGRAMMING

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.
AIM:
Program to calculate the discriminate D and basing on value of D,
describe the nature of roots of the quadratic equation ax2+bx=0.

SOURCE CODE:
import java.util.*;
import java.lang.*;
class Quatratic_eq_roots
{

public static void main(String[] args)


{
double a,b,c;
double root1, root2;
Scanner q= new Scanner(System.in);
System.out.println("Enter the first co-efficient:");
a=q.nextFloat() ;
System.out.println("Enter the second co-efficient:");
b=q.nextFloat() ;
System.out.println("Enter the third co-efficient:");
c=q.nextFloat() ;

//if a is equal to 0 its a linear equation


if(a==0)

20JG5A0503 3|Page
|| CSE R19 JAVA PROGRAMMING

{
System.out.println("EQUATION IS LINEAR.\nROOTS ARE
NOT DETERMINED.\nMUST a NOTEQUAL TO 0(a!=0) ");
}

//if a is not equal to 0


else
{

// calculate the determinant (b2 - 4ac)


double discriminant = b * b - 4 * a * c;
System.out.println("The discriminant is "+discriminant);
double positive_root= (-
b+Math.sqrt(discriminant))/(2*a);
double negative_root=
(-b-Math.sqrt(discriminant))/(2*a);

// check if determinant is greater than "0"


if (discriminant > 0)
{

// two real and distinct roots


System.out.format("The roots are x = "+negative_root+" ,
"+positive_root);
}
// check if determinant is equal to 0
else if (discriminant == 0)

20JG5A0503 4|Page
|| CSE R19 JAVA PROGRAMMING

// two real and equal roots


// determinant is equal to 0
// so -b + 0 == -b
root1 = root2 = -b / (2 * a);
System.out.println("root1 = root2 ="+root1);
}
// if determinant is less than zero
else
{

// roots are complex number and distinct


double real = -b / (2 * a);
double imaginary = Math.sqrt(-discriminant) / (2 * a);
System.out.format("root1 ="+real,"+i"+imaginary);
System.out.format("\nroot2 ="+real,"+i"+imaginary);
}//inner else close
}//outer else close
}//main close
}//class close

INPUT/OUTPUT:
Case:1

20JG5A0503 5|Page
|| CSE R19 JAVA PROGRAMMING

Case2:

Case:3

20JG5A0503 6|Page
|| CSE R19 JAVA PROGRAMMING

Case:4

20JG5A0503 7|Page
NAME: CH. Rohitha Anupama REGNO: 20JG5A0503

|| CSE R19 JAVA PROGRAMMING

EXERCISE:1-(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.

AIM:
Java program to take input as the speed of each racers and print
back the speed of qualified racer whom containing the speed is
greater than average

SOURCE CODE:
import java.util.*;
import java.lang.*;
class racedemo
{
public static void main(String[] args)
{
float []a;
a=new float[10];
float average;
float num;
int i,sum=0;

Scanner r=new Scanner(System.in);

20JG5A0503 8|Page
|| CSE R19 JAVA PROGRAMMING

System.out.println("enter how many racers you want to be in the


race for qualification:");

num=r.nextFloat();

//the repetation to take the input from the user


for(i=0;i<num;i++)
{
System.out.println("enter the speed of racer "+(i+1)+" is :");

//storing the inputed values in the form of array in a[i]


a[i]=r.nextFloat();

//addtion of all inputed values


sum+=a[i];
}

//calculating average
average=sum/num;
System.out.println("average speed is:"+average);

//this loop is used to check the condiontion


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

//if the inputed value is greater than average


if(a[i]>average)
{
20JG5A0503 9|Page
|| CSE R19 JAVA PROGRAMMING

System.out.println("The bike racer "+(i+1)+" has qualified the


race with speed "+a[i]);
}
}
System.out.println("No more racers are qualified to the race.");
}
}

INPUT/OUTPUT:
Case:1

20JG5A0503 10 | P a g e
|| CSE R19 JAVA PROGRAMMING

Case:2

20JG5A0503 11 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Operations, Expressions, Control-flow,

Strings)

EXERCISE:2-(a)
Write a JAVA program to search for an element in a given list of
elements using binary search mechanism.

AIM:
Program to search for an element in a given list of elements using
binary search mechanism.

SOURCE CODE:
import java.util.Scanner;
class binarysearch
{
public static void main(String args[])
{
int n, i,j,temp,num,first, last, middle,k=0;
int a[ ]=new int[20];

//To obtain input to the variables


Scanner b = new Scanner(System.in);

//To enter how many elements to enter


System.out.println("Enter total number of elements:");
20JG5A0503 12 | P a g e
NAME: CH. Rohitha Anupama REGNO: 20JG5A0503

|| CSE R19 JAVA PROGRAMMING

//to input an integer value from the user and assign it to the
variable n
n = b.nextInt();

//To enter the elements in asscending order


System.out.println("Enter elements one by one:");

//to repeat until the count of elements n


for (i = 0; i < n; i++)
{
//the a[i] it stores the list of integers in array
a[i] = b.nextInt();
}

System.out.println("The elements before sorted:");


for(i=0;i<n;i++)
{
System.out.print("\t"+a[i]);
}
System.out.println("\nEnter the search value:");

//the search value was stored in num


num = b.nextInt();
//it repeats up to the specified length of n

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

20JG5A0503 13 | P a g e
|| CSE R19 JAVA PROGRAMMING

//it repeats up to the specified n value minus one(5-1=4) it will reat upt
to 4 times
for(j=0;j<n-1;j++)
{

//if the value if a[j] is less than a[j+1]


if(a[j]<a[j+1])
{
k=1;
}
}
}

//it repeats up to the specified length of n


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

//it specified up the n value minus one(5-1=4) it will reat upt to 4 times
for(j=0;j<n-1;j++)
{

//if the value if a[j] is greater than a[j+1]


if(a[j]>a[j+1])
{
//swapping of elements are done

20JG5A0503 14 | P a g e
|| CSE R19 JAVA PROGRAMMING

temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
k=2;
}
}
}
switch(k)
{
case 1:

System.out.println("the elements are in sorted order,no


operation is done.");
break;
case 2:
System.out.println("The elements after sorted:");
for(i=0;i<n;i++)
{
System.out.print("\t"+a[i]);
}
break;
}
first = 0;
last = n - 1;
middle = (first + last)/2;

20JG5A0503 15 | P a g e
|| CSE R19 JAVA PROGRAMMING

//it repeats until the first value is lessthan or equal to last value
while( first <= last )
{

//if the middle values is less than num


if ( a[middle] < num )
first = middle + 1;

//if the middle value is equal to num value


else if ( a[middle] == num )
{
System.out.println("\nNumber Found");
break;
}

//if the middle value is greater than num


else
{
last = middle - 1;
}
middle = (first + last)/2;
}

//if the first value is greater than last


if ( first > last )
System.out.println( " \nNumber is not found");
}
20JG5A0503 16 | P a g e
|| CSE R19 JAVA PROGRAMMING

INPUT/OUTPUT:
Case:1

Case:2

20JG5A0503 17 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 18 | P a g e
NAME: CH. Rohitha Anupama REGNO: 20JG5A0503

|| CSE R19 JAVA PROGRAMMING

EXERCISE:2-(b)
Write a JAVA program to sort for an element in a given list of
elements using bubble sort.

AIM:
Program to sort for an element in a given list of elements using
bubble sort.

SOURCE CODE:
import java.util.Scanner;
class bubblesort
{
public static void main(String args[])
{
int i,n,temp,j,k=0;
int a[]=new int[20];

Scanner bu=new Scanner(System.in);

System.out.println("Enter how many elements you want to be


sorted:");

n=bu.nextInt();
System.out.println("Enter the elements in sorted or unsorted
order:");

20JG5A0503 19 | P a g e
|| CSE R19 JAVA PROGRAMMING

//It is used to take the input and store it in array form.


for(i=0;i<n;i++)
{
a[i]=bu.nextInt();
}

//it repeats up to the specified length of n


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

//it repeats up to the specified n value minus one(5-1=4) it will reat upt
to 4 times
for(j=0;j<n-1;j++)
{

//if the value if a[j] is less than a[j+1]


if(a[j]<a[j+1])
{
k=1;
}
}
}
//it repeats up to the specified length of n
for(i=0;i<n;i++)
{

//it specified up the n value minus one(5-1=4) it will reat upt to 4 times
20JG5A0503 20 | P a g e
|| CSE R19 JAVA PROGRAMMING

for(j=0;j<n-1;j++)
{

//if the value if a[j] is greater than a[j+1]


if(a[j]>a[j+1])
{
//swapping of elements are done
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
k=2;
}
}
}
switch(k)
{
case 1:
System.out.println("the elements are in sorted order,no
operation is done.");
break;
case 2:
System.out.println("The elements after sorted:");
for(i=0;i<n;i++)
{
System.out.print("\t"+a[i]);
}
break;
20JG5A0503 21 | P a g e
|| CSE R19 JAVA PROGRAMMING

}
}
}

INPUT/OUTPUT:

Case:1

Case:2

20JG5A0503 22 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 23 | P a g e
|| CSE R19 JAVA PROGRAMMING

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

AIM:
Program to sort for an element in a given link of element using
merge sort.

SOURCE CODE:
//to implement mergesort program.
import java.util.Scanner;
public class MergeSort
{
void merge(int arr[], int beg, int mid, int end)
{

int l = mid - beg + 1;


int r = end - mid;

int LeftArray[] = new int [l];


int RightArray[] = new int [r];

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


LeftArray[i] = arr[beg + i
for (int j=0; j<r; ++j)
RightArray[j] = arr[mid + 1+ j];

20JG5A0503 24 | P a g e
|| CSE R19 JAVA PROGRAMMING

int i = 0, j = 0;
int k = beg;
while (i<l&&j<r)
{
if (LeftArray[i] <= RightArray[j])
{
arr[k] = LeftArray[i];
i++;
}
else
{
arr[k] = RightArray[j];
j++;
}
k++;
}
while (i<l)
{
arr[k] = LeftArray[i];
i++;
k++;
}
while (j<r)
{
arr[k] = RightArray[j];
j++;

20JG5A0503 25 | P a g e
|| CSE R19 JAVA PROGRAMMING

k++;
}
}

void sort(int arr[], int beg, int end)


{
if (beg<end)
{
int mid = (beg+end)/2;

//calling methods in another mothod.


sort(arr, beg, mid);
sort(arr , mid+1, end);
merge(arr, beg, mid, end);
}
}
public static void main(String args[])
{

int i,n;
Scanner m=new Scanner(System.in);
System.out.println("enter the number of elements in the
array:");
n=m.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements of the array one by
one:");

20JG5A0503 26 | P a g e
|| CSE R19 JAVA PROGRAMMING

for(i=0;i<n;i++)
{
arr[i]=m.nextInt();
}

//object is created to access the methods on same class


MergeSort ob = new MergeSort();

//y this object accing the method


ob.sort(arr, 0, arr.length-1);

System.out.println("\nSorted array");
for(i =0; i<arr.length;i++)
{
System.out.print(“\t”+arr[i]);
}
}
}

INPUT/OUTPUT:

20JG5A0503 27 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 28 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:(2(d))
Write a JAVA program using StringBuffer to delete, remove
character

AIM:
Program to write a JAVA program using StringBuffer to delete,
remove character

SOURCE CODE:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello Everyone");
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 Everyone");
sb3.deleteCharAt(4);
System.out.println(sb3);
}
}

INPUT/OUTPUT:

20JG5A0503 29 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 30 | P a g e
|| CSE R19 JAVA PROGRAMMING

CLASS, OBJECTS

EXERCISE:3(a)
Write a JAVA program to implement class mechanism. Create a
class, methods and invoke them inside main method.

AIM:
Program to implement class mechanism and to create a class ,
method and invoke them inside the main method.

SOURCE CODE:
import java.util.Scanner;
class method
{
void display()
{
int l=50,b=90;
System.out.println("with no return type and no parameter-
list:");
System.out.println("the length is:"+l);
System.out.println("the breath is:"+b);
}
void area_of_rec(int l,int b)
{

System.out.println("with no return type and with parameter-


list:");

20JG5A0503 31 | P a g e
|| CSE R19 JAVA PROGRAMMING

int area=l*b;
System.out.println("the area of rectangle is:"+area);
}
int area_of_tri()
{
System.out.println("with return type and no parameter-list:");
int h=10,b=20;
int area=h*(b/2);
return area;
}
int area_of_sq(int s)
{
System.out.println("with return type and with parameter-list:");
return (s*s);
}
}

class Invoke_method_inside_main
{
public static void main(String args[])
{
int l,b,s;
Scanner mm=new Scanner(System.in);
System.out.println("enter the length:");
l=mm.nextInt();
System.out.println("enter the breath:");
b=mm.nextInt();
20JG5A0503 32 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("enter the side:");


s=mm.nextInt();
method m=new method();
m.display();
m.area_of_rec(l,b);
int t=m.area_of_tri();
System.out.println("the area of triangle is:"+t);
int S=m.area_of_sq(s);
System.out.println("the area of square is:"+S);
}
}

INPUT/OUTPUT:

20JG5A0503 33 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:3-(b)
Write a JAVA program to implement constructor.

AIM:
Program to implement constructor.

SOURCE CODE:
import java.util.Scanner;
class implement_con
{
int l,b;
implement_con()
{
System.out.println("It is a default constructor");
l=20;
b=30;
}
int area_of_rec()
{
int area=l*b;
return area;
}
int a;
implement_con(int s)
{
System.out.println("it is a parameterized constructor:");
a=s;

20JG5A0503 34 | P a g e
|| CSE R19 JAVA PROGRAMMING

}
int area_of_sq()
{
return a*a;
}
}
class constructor
{
public static void main(String args[])
{
int s;
Scanner con=new Scanner(System.in);
System.out.println("enter the side:");
s=con.nextInt();
implement_con c=new implement_con();
int tir=c.area_of_rec();
System.out.println("the area of rectangle is:"+tir);
implement_con co=new implement_con(s);
int sq=co.area_of_sq();
System.out.println("the area of square is:"+sq);
}
}

INPUT/OUTPUT:

20JG5A0503 35 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 36 | P a g e
|| CSE R19 JAVA PROGRAMMING

(METHODS)

EXERCISE:4-(a)
Write a JAVA program to implement constructor overloading .

AIM:
Program to implement constructor overloading.

SOURCE CODE:
import java.util.Scanner;
class constructor
{
int s;
constructor()
{
System.out.println("It is a default constructor");
s=4;
}
constructor(int a)
{
System.out.println("it is a parameterized constructor:");
s=a;
}
int area_of_sq()
{
return s*s;
}
}

20JG5A0503 37 | P a g e
|| CSE R19 JAVA PROGRAMMING

class con_overloading
{
public static void main(String args[])
{
int side;
Scanner c_over=new Scanner(System.in);
System.out.println("enter the side:");
side=c_over.nextInt();
constructor c=new constructor();
int a1=c.area_of_sq();
System.out.println("the area of square is:"+a1);
constructor co=new constructor(side);
int a2=co.area_of_sq();
System.out.println("the area of square is:"+a2);
}
}

INPUT/OUTPUT:

20JG5A0503 38 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:4-(b)

20JG5A0503 39 | P a g e
|| CSE R19 JAVA PROGRAMMING

Write a JAVA program to implement method overloading .

AIM:
program to implement method overloading.

SOURCE CODE:
import java.util.Scanner;
class method
{
int l=10,b=20;
int area_of_rec()
{
System.out.println("with return type and no parameter-list:");
return l*b;
}
int area_of_rec(int l,int b)
{
System.out.println("with return type and with parameter-
list:");
return l*b;
}
}
class method_overloading
{
public static void main(String args[])
{
int l,b;
Scanner mo=new Scanner(System.in);

20JG5A0503 40 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("enter the length:");


l=mo.nextInt();
System.out.println("enter the breath:");
b=mo.nextInt();
method m1=new method();
int o1=m1.area_of_rec();
System.out.println("the area of rectangle is:"+o1);
method m2=new method();
int o2=m2.area_of_rec(l,b);
System.out.println("the area of rectangle is:"+o2);
}
}

INPUT/OUTPUT:

20JG5A0503 41 | P a g e
|| CSE R19 JAVA PROGRAMMING

(INHERITANCE)

EXERCISE:5-(a)
Write a JAVA program to implement Single Inheritance.

AIM:
Program to implement Single Inheritance.

SOURCE CODE:
import java.util.Scanner;
class Single_inheritance
{

20JG5A0503 42 | P a g e
|| CSE R19 JAVA PROGRAMMING

int a=10;
Single_inheritance()
{
System.out.println("the construtor in parent class.");
}
int display1(){
int f=a*a;
return(f);
}
}
class Single extends Single_inheritance
{
int l,b;
Single(int c,int d)
{
l=c;
b=d;
}
int display()
{
System.out.println("I am a child of single_inheritance");
int e=l*b;
return(e);
}
}
class sing_inheri
{
20JG5A0503 43 | P a g e
|| CSE R19 JAVA PROGRAMMING

public static void main(String args[])


{
int a,b;
Scanner s = new Scanner(System.in);
System.out.println("Enter the a value:");
a=s.nextInt();
System.out.println("Enter the b value:");
b=s.nextInt();
Single ob=new Single(a,b);
int w=ob.display1();
System.out.println("area of square:"+w);
int r=ob.display();
System.out.println("area of rectangle:"+r);
}
}

INPUT/OUTPUT:

20JG5A0503 44 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 45 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:5-(b)
Write a JAVA program to implement multilevel Inheritance

AIM:
program to implement multilevel Inheritance

SOURCE CODE:
import java.util.Scanner;
import static java.lang.Math.*;
class sq_area
{
int a=10;
sq_area()
{
System.out.println("This is a constructor of parenet sq_area");
}
int reveal()
{
int e=a*a;
return(a);
}
}
class rec_area extends sq_area
{
int l=40;
int b=10;
rec_area

20JG5A0503 46 | P a g e
|| CSE R19 JAVA PROGRAMMING

{
System.out.println("\nThis is a constructor of parenet rec_area");
}
int show()
{
int f=l*b;
return(f);
}
}
class cir_area extends rec_area
{
int r;
cir_area(int r)
{
this.r=r;
System.out.println("\nThis is a constructor is a child of sq_area
and rec_area parent classes");
}
double display()
{
double g=Math.PI*r*r;
return(g);

}
}
class main_area
{

20JG5A0503 47 | P a g e
|| CSE R19 JAVA PROGRAMMING

public static void main(String args[])


{
int h;
Scanner s = new Scanner(System.in);
System.out.println("Enter the a value:");
h=s.nextInt();
cir_area i=new cir_area(10);
int e=i.reveal();
System.out.println("\nthe area of square:"+e);
int f=i.show();
System.out.println("\nthe area of rectangle:"+f);
double g=i.display();
System.out.println("\nthe area of circle:"+g);
}
}

INPUT/OUTPUT:

20JG5A0503 48 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:5-(c)

20JG5A0503 49 | P a g e
|| CSE R19 JAVA PROGRAMMING

Write a java program for abstract class to find areas of different


shapes

AIM:
Java program for abstract class to find areas of different shapes

SOURCECODE:
import java.util.Scanner;
abstract class shape
{
abstract double area(double l ,double b,double s);
}
class rectangle extends shape
{
double area(double l , double b,double s)
{
return l*b;
}
}
class triangle extends shape
{
double area(double b, double h,double s)
{
return 0.5*b*h;
}
}
class square extends shape
{

20JG5A0503 50 | P a g e
|| CSE R19 JAVA PROGRAMMING

double area(double l,double b,double s)


{
return s*s;
}
}
class shapedemo
{
public static void main(String[] args)

{
double l,b,s;
Scanner a=new Scanner(System.in);
System.out.println("Enter the length:");
l=a.nextDouble();
System.out.println("Enter the breath:");
b=a.nextDouble();
System.out.println("Enter the side:");
s=a.nextDouble();
rectangle r1=new rectangle();
triangle t1=new triangle();
square s1=new square();
System.out.println("The area of rectangle is:"+r1.area(l,b,s));
System.out.println("The area of triangle is: "+t1.area(l,b,s));
System.out.println("The area of square is: "+s1.area(l,b,s));
}
}

20JG5A0503 51 | P a g e
|| CSE R19 JAVA PROGRAMMING

INPUT/OUTPUT:

INHERITANCE(CONTINUED)

20JG5A0503 52 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:6-(a)
Write a JAVA program give example for “super” keyword

AIM:
JAVA program give example for “super” keyword

SOURCECODE:
import java.util.*;
class super_demo
{
int l,s;
super_demo()
{
System.out.println("\nThis is a non parametarized
constructor-\n which is returning the out of area of rectangle:");
l=10;
}
super_demo(int s)
{
this.s=s;
System.out.println("\nThis is a one parametarized
constructor-\n which is returning the out of area of Square:");
}
}
class super_class extends super_demo
{
int b;

20JG5A0503 53 | P a g e
|| CSE R19 JAVA PROGRAMMING

super_class()
{
super();
b=10;
}
int area()
{
return l*b;
}
super_class(int s)
{
super(s);
}
int area1()
{
return s*s;
}
}
class Superdemo
{
public static void main(String args[])
{
int s;
Scanner a=new Scanner(System.in);
System.out.println("Enter the side :");
s=a.nextInt();
super_class a1=new super_class();
20JG5A0503 54 | P a g e
|| CSE R19 JAVA PROGRAMMING

int r=a1.area();
System.out.println("\nThe area of rectangle is:"+r);
super_class a2=new super_class(s);
int t=a2.area1();
System.out.println("\nThe area of square is:"+t);
}
}

INPUT/OUTPUT:

EXERCISE:6-(b)

20JG5A0503 55 | P a g e
|| CSE R19 JAVA PROGRAMMING

Write a JAVA program to implement Interface. What kind of


Inheritance can be achieved?

AIM:
JAVA program to implement Interface.
DESCRIPTION:

 Interface is a 100% abstract class.


 It contains only constants and method signatures.
 it is a reference type similar to class. An interface can’t be
instantiated. It can be implemented by a class or extended by
another interface.

 Interfaces provide an alternative to multiple inheritance. Java


programming language does not support multiple inheritance. But
interfaces provide a good solution. Any class can implement a
particular interface and importantly the interfaces are not a part
of class hierarchy. So, the general rule is extend one but
implement many. A class can extend just one class but it can
implement many interfaces. So, here we have multiple types for a
class. It can be of the type of its super class and all the interfaces
it implements.

SOURCE CODE:
import java.util.*;
interface Dimensions

20JG5A0503 56 | P a g e
|| CSE R19 JAVA PROGRAMMING

{
int area(int l,int b);
}
interface Area extends Dimensions
{
void show();
}
class rectangle
{
public int area(int l, int b)
{
return l*b;

}
public void show()
{
System.out.println("this is a interface area ");
}
}
class interface_demo
{
public static void main (String args[])
{
int l,b,e;
Scanner a=new Scanner(System.in);
System.out.println("the length is:");
l=a.nextInt();

20JG5A0503 57 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("the breath is:");


b=a.nextInt();
rectangle s=new rectangle();
e=s.area(l,b);
System.out.println("the area of rectangle is:"+e);

}
}

INPUT/OUTPUT:

20JG5A0503 58 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Exception)

Exercise - 7
Write a JAVA program that describes exception handling

mechanism

AIM:
JAVA program that implements Runtime polymorphism

SOURCE CODE:
class exception_handing
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally{

20JG5A0503 59 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("INthe finally block.");


}
System.out.println("After the Try-catch-finally
statement");
}
}
INPUT/OUTPUT:

20JG5A0503 60 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:7(b)
write a JAVA program Illustrating Multiple catch

AIM:
JAVA program Illustrating Multiple catch polymorphism

SOURCE CODE:
class multitrydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
20JG5A0503 61 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println(e);
}
System.out.println("After the catch statement");
}
}
INPUT/OUTPUT:

20JG5A0503 62 | P a g e
|| CSE R19 JAVA PROGRAMMING

RUNTIME POLYMORPHISM

EXERCISE:8(a)
Write a JAVA program that implements Runtime polymorphism

AIM:
JAVA program that implements Runtime polymorphism

SOURCE CODE:
class auto
{
void fuel()
{
System.out.println("\nthis is a parent class of both classes");
System.out.println("auto use desiel fuel to work");
}
}
class bike extends auto
{
void fuel()
{
System.out.println("\nthis is a child class of auto");
System.out.println("Bike use petrol fuel to work");
}
}
class car extends auto
{
void fuel()

20JG5A0503 63 | P a g e
|| CSE R19 JAVA PROGRAMMING

{
System.out.println("\nthis is a child class of auto");
System.out.println("Car use both petrol and desiel to work");
}
}
class poly_runtime
{
public static void main(String args[])
{
auto obj0=new auto();
bike obj1=new bike();//upcasting
car obj2=new car();//upcasting
auto var;//create an object for class auto
var=obj0;
var.fuel();
var=obj1;//access the bike object by using auto object
var.fuel();
var=obj2;
var.fuel();
}
}

INPUT/OUTPUT:

20JG5A0503 64 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 65 | P a g e
|| CSE R19 JAVA PROGRAMMING

EXERCISE:8-(b)

Write a Case study on run time polymorphism,

inheritance that implements in above problem

AIM:

Case study on run time polymorphism,

inheritance that implements in above problem

Case Study:

DESCRIPTION:
Dynamic method dispatch (Runtime-polymorphism) is the mechanism
by which a call to an overridden method is resolved at run time, rather
than compile time.

 Dynamic method dispatch which is also referred as run time


polymorphism.

 Dynamic method dispatch is a technique by which call to a


overridden method is resolved at runtime, rather than compile
time.When an overridden method is called by a reference, then
which version of overridden method is to be called is decided at
runtime according to the type of object it refers.Dynamic method
dispatch is performed by JVM not compiler.
Dynamic method dispatch allows java to support overriding of
methods and perform runtime polymorphism.It allows subclasses to
have common methods and can redefine specific implementation for

20JG5A0503 66 | P a g e
|| CSE R19 JAVA PROGRAMMING

them.This lets the superclass reference respond differently to same


method call depending on which object it is pointing.

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.

SOURCECODE:(without upcasting)
class Vehicle{
public void move(){
System.out.println("Vehicles can move!!");
}
}

class MotorBike extends Vehicle{


public void move(){
20JG5A0503 67 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("MotorBike can move and accelerate too!!");


}
}

class runtime_polymorphism{
public static void main(String[] args){
Vehicle vh1=new Vehicle();
Vehicle vh=new MotorBike(); //upcasting
vh1.move();
vh.move();
}
}

INPUT/OUTPUT:

SOURCE CODE:(FOR UPCASTING)


20JG5A0503 68 | P a g e
|| CSE R19 JAVA PROGRAMMING

class Vehicle{
public void move(){
System.out.println("Vehicles can move!!");
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println("MotorBike can move and accelerate too!!");
}
}

class runtime_polymorphism{
public static void main(String[] args){
Vehicle vh=new Vehicle();
MotorBike vh1=new MotorBike();
Vehicle var;
var=vh;
var.move();
var=vh1;
var.move();
}
}

INPUT/OUTPUT:

20JG5A0503 69 | P a g e
|| CSE R19 JAVA PROGRAMMING

(User defined Exception)

20JG5A0503 70 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 9
write a JAVA program for creation of Illustrating throw.

AIM:
JAVA program for creation of Illustrating throw

Source code:
class throw_excep
{
public static void main(String args[])
{
try
{
int a=10/0;
throw new Exception ("There is mo value to print.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Input/output:

20JG5A0503 71 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 72 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 9(b)
write a JAVA program for creation of Illustrating finally.

AIM:
JAVA program for creation of Illustrating finally.

Source code:
Class finally_ex
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally

20JG5A0503 73 | P a g e
|| CSE R19 JAVA PROGRAMMING

{
System.out.println("This is inside finally
block");
}
}
}
Input/output:

20JG5A0503 74 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 9(c)
write a JAVA program for creation of Java Built-in

Exceptions

AIM:
JAVA program for creation of Java Built-in Exceptions

Source code:
import java.util.Scanner;
class Built_Exceptiondemo
{
public static void main(String args[])
{
try
{
Scanner q= new Scanner(System.in);
System.out.println("Enter the a value:");
int a=q.nextInt() ;
System.out.println("Enter the b value:");
int b=q.nextInt() ;
System.out.println("the a value: "+a);
System.out.println("the b value: "+b);
int c = a/b;
System.out.println ("the value is: "+c);
System.out.println("\nEnter the string value: ");
String f=q.next();

20JG5A0503 75 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("the value is : "+f);


System.out.println("the character at 0 is: "+f.charAt(0));
System.out.println("\nEnter the string value: ");
String s=q.next();
int num = Integer.parseInt (s) ;
System.out.println("the interget value is which is converted
from string is " +num);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}

Input/output:
Case:1

20JG5A0503 76 | P a g e
|| CSE R19 JAVA PROGRAMMING

Case2:

Case3:

20JG5A0503 77 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 78 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 9(d)
write a JAVA program for creation of Java user-defined

Exceptions

AIM:
JAVA program for creation of Java user-defined

Exceptions

Source code:
import java.lang.*;
import java.util.*;
class Stack_over_flowException extends Exception{
Stack_over_flowException(String s){
super(s);
}
}
class Stack_under_flowException extends Exception{
Stack_under_flowException(String s){
super(s);
}
}

class Custom_Exception{
int[] item;
int stackTop;

20JG5A0503 79 | P a g e
|| CSE R19 JAVA PROGRAMMING

public void ArrayStack( int size )


{
item = new int[size]; // Make array
stackTop = 0;
}

public void push( int x ) throws Stack_over_flowException


{
if ( stackTop == item.length )
{
throw new Stack_over_flowException("Stack is full, you cannot
do push operation.");
}

item[stackTop] = x; // Store x in next slot


stackTop++; // Advance one slot location
}

public void pop ( ) throws Stack_under_flowException


{
int returnItem;

if ( stackTop == 0 )
{
throw new Stack_under_flowException("Stack is empty, you
cannot do pop operation.");
}

20JG5A0503 80 | P a g e
|| CSE R19 JAVA PROGRAMMING

returnItem = item[ stackTop-1 ]; // Get last stored item


stackTop--;
}
}
class Userdefined_Exception_ex{
public static void main( String[] args )
{
int x;
Custom_Exception s=new Custom_Exception();
System.out.println("Enter number size of the stack: ");
Scanner c=new Scanner(System.in);
int y=c.nextInt();
s.ArrayStack( y ); // Will cause underflow
System.out.println("CHOOSE ONE");
System.out.println("0.exit\n1.PUSH\n2.POP\n");
int k=c.nextInt();
do{
switch(k)
{
case 1:
{
try
{
System.out.println("if you want to push numbers in
stack if yes type how many you want to push (or) otherwise
type(0)?\n");

20JG5A0503 81 | P a g e
|| CSE R19 JAVA PROGRAMMING

int v=c.nextInt();
while(v>=1){
System.out.println("Enter number");
x = c.nextInt();
s.push(x);
System.out.println("push(" + x + ")");
v--;
}
}
catch ( Exception e )
{

System.out.println("Error detected: " + e);


}
break;
}
case 2:
{
try{
System.out.println("if you want to pop numbers in
stack if yes type how many you want to pop (or) otherwise
type(0)?\n");
int v=c.nextInt();
while(v>=1){
System.out.println("Enter number");
x = c.nextInt();
s.pop();

20JG5A0503 82 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("pop() ---> " + x );


v--;
}
}
catch ( Exception e )
{
System.out.println("Error detected: " + e);
}
break;
}
case 0:
{
break;
}
}
System.out.println("CHOOSE ONE");
System.out.println("0.exit\n1.PUSH\n2.POP\n");
k=c.nextInt();
} while(k!=0);
}
}

Input/output:
Case:1(with no exception)

20JG5A0503 83 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 84 | P a g e
|| CSE R19 JAVA PROGRAMMING

Case2(with exception)

20JG5A0503 85 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 86 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Threads)

Exercise – 10(a(i))
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

AIM:
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

Source code:
class Thread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000);

20JG5A0503 87 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Thread2 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);
}
}
}
20JG5A0503 88 | P a g e
|| CSE R19 JAVA PROGRAMMING

class Thread3 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 thread_demo
{
public static void main(String args[])
{
Thread1 a1=new Thread1();
Thread2 b1=new Thread2();
Thread3 c1=new Thread3();
a1.start();
b1.start();
20JG5A0503 89 | P a g e
|| CSE R19 JAVA PROGRAMMING

c1.start();
}
}

Input/output:

Exercise – 10(a(ii))
20JG5A0503 90 | P a g e
|| CSE R19 JAVA PROGRAMMING

write a JAVA program that creates threads by extending

Runnable 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

AIM:
JAVA program that creates threads by extending

Runnsable 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

Source code:
class Thread1 implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good morning");
}

20JG5A0503 91 | P a g e
|| CSE R19 JAVA PROGRAMMING

}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Thread2 implements Runnable
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Thread3 implements Runnable
{
20JG5A0503 92 | P a g e
|| CSE R19 JAVA PROGRAMMING

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);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
Thread1 a1=new Thread1();
Thread2 b1=new Thread2();
Thread3 c1=new Thread3();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
20JG5A0503 93 | P a g e
|| CSE R19 JAVA PROGRAMMING

t2.start();
t3.start();
}
}

Input/output:

20JG5A0503 94 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 95 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 10(b)
write a program illustrating isAlive and join ()

AIM:
program illustrating isAlive and join ()

Source code:
class Thread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000);
System.out.println("Thread1: good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Thread2 extends Thread

20JG5A0503 96 | P a g e
|| CSE R19 JAVA PROGRAMMING

{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("Thread2: hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Thread3 extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("Thread3: welcome");
20JG5A0503 97 | P a g e
|| CSE R19 JAVA PROGRAMMING

}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class isalive_prog
{
public static void main(String args[])
{
Thread1 a1=new Thread1();
Thread2 b1=new Thread2();
Thread3 c1=new Thread3();
a1.start();
b1.start();
c1.start();
System.out.println("the thread is alive or not: "+a1.isAlive());
System.out.println("the thread is alive or not: "+b1.isAlive());
System.out.println("the thread is alive or not: "+c1.isAlive());
try
{
a1.join();
b1.join();
c1.join();
}
20JG5A0503 98 | P a g e
|| CSE R19 JAVA PROGRAMMING

catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("the thread is alive or not: "+a1.isAlive());
System.out.println("the thread is alive or not: "+b1.isAlive());
System.out.println("the thread is alive or not: "+c1.isAlive());
}
}

Input/output:

20JG5A0503 99 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 100 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 10(c)
write a Program illustrating Daemon Threads

AIM:
Program illustrating Daemon Threads

Source code:
class Thread1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
System.out.println("daemon thread is working now");
else
System.out.println("user thread working now");
}
}
class daemondemo
{
public static void main(String[] args)
{
Thread1 a1=new Thread1();
Thread1 a2=new Thread1();
Thread1 a3=new Thread1();
a1.setDaemon(true);
a1.start();

20JG5A0503 101 | P a g e
|| CSE R19 JAVA PROGRAMMING

a2.start();
a3.start();
}
}

Input/output:

20JG5A0503 102 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Threads continuity)

Exercise – 11(a)

Write a JAVA program Producer Consumer

Problem

AIM:

JAVA program Producer Consumer Problem

Source code:
class use
{
int n;
boolean b=false;
synchronized int get()
{
if(!b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n);
20JG5A0503 103 | P a g e
|| CSE R19 JAVA PROGRAMMING

b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n;
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
use a1;
Thread t1;
producer(use a1)
{
20JG5A0503 104 | P a g e
|| CSE R19 JAVA PROGRAMMING

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
{
use a1;
Thread t1;
consumer(use a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
20JG5A0503 105 | P a g e
|| CSE R19 JAVA PROGRAMMING

}
}
}
class produ_consu_demo
{
public static void main(String args[])
{
use a1=new use();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}

Input/output:

20JG5A0503 106 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 11(b)
write a case study on thread Synchronization

after solving the above producer consumer

problem

AIM:
case study on thread Synchronization after

solving the above producer consumer problem

Source code:

 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
e.g.Producer 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.

20JG5A0503 107 | P a g e
|| CSE R19 JAVA PROGRAMMING

 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. Always call wait(), notify() and notifyAll() methods from
synchronized method or synchronized block otherwise JVM will
throw IllegalMonitorStateException
2) 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.
3) Always call wait in shared object e.g. shared queue in this
example.
4) Prefer notifyAll() over notify() method due to reasons given in
this article

20JG5A0503 108 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Packages)

Exercise – 12(a)
write a JAVA program illustrate class path

AIM:
JAVA program illustrate class path

Source code:
import java.net.URL;
import java.net.URLClassLoader;
public class App
{
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());
}
}
}

Input/output:

20JG5A0503 109 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 110 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 12(b)
write a case study on including in class path in

your os environment of your package.

AIM:
case study on including in class path in your os

environment of your package.

Source c:

 The differences between path and classpath are given by.


(1) The PATH is an environment variable used to locate "java"
or "javac" command, to run java program and compile java
source file. The CLASSPATH is an environment variable used to
set path for java classes.
(2) In order to set PATH in Java, we need to include bin
directory in PATH environment while in order to set CLASSPATH
we need to include all directories where we have put either our
.class file or JAR file, which is required by our Java application.
(3) PATH environment variable is used by operating system
while CLASSPATH is used by Java ClassLoaders to load class
files.
(4) Path refers to the system while classpath refers to the
Developing Environment.
 By default the java run time system uses the current working
directory.

20JG5A0503 111 | P a g e
|| CSE R19 JAVA PROGRAMMING

 Normally to execute a java program in any directory we have to


set the path by as follows

Setting environmental variable in windows 10:

Step-1:

 Select My computer on the desktop and right click the


mouse and then select properties.
 It displays the following “System Properties” dialog.

set path= c:\Program Files\java\jdk1.16.0_10\bin;

20JG5A0503 112 | P a g e
|| CSE R19 JAVA PROGRAMMING

Step-2:

 In System Properties click Advanced and then click Environment


Variables.
 It displays the following “Environment Variables” dialog.

20JG5A0503 113 | P a g e
|| CSE R19 JAVA PROGRAMMING

Step-3:

 In Environment Variables click New in System variables.


 It displays the following “New System Variable” dialog box.

20JG5A0503 114 | P a g e
|| CSE R19 JAVA PROGRAMMING

Step-4:

 Now type variable name as a path and then variable value as


 c:\Program Files\java\jdk1.15.0_10\*.jar;

Step-5:

Click OK

20JG5A0503 115 | P a g e
|| CSE R19 JAVA PROGRAMMING

Click OK

20JG5A0503 116 | P a g e
|| CSE R19 JAVA PROGRAMMING

The CLASSPATH is created.

20JG5A0503 117 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 12(c)
write a JAVA program that import and use the defined

your package in the previous Problem

AIM:

JAVA program that import and use the defined your

package in the previous Problem

Source code:

(i) Creating a package:

package Gas.solids;

public class solid{


public void display(){
System.out.println("Molecules arranged in
regular.");
}
public static void main(String args[]){
solid a=new solid();
a.display();
}
}

Input/output:
20JG5A0503 118 | P a g e
|| CSE R19 JAVA PROGRAMMING

(ii) importing a package:


import Gas.solids.solid;

class iron{
void show(){
System.out.println("Iron: ");
}
}
class mole{
public static void main(String args[]){
Gas.solids.solid s=new Gas.solids.solid();
iron i=new iron();

20JG5A0503 119 | P a g e
|| CSE R19 JAVA PROGRAMMING

i.show();
s.display();
}
}

Input/output:

20JG5A0503 120 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Applets)

Exercise – 13(a)
write a JAVA program to paint like paint brush in

applet

AIM:

JAVA program to paint like paint brush in applet

Source code:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class Paintbrush extends Applet implements


MouseMotionListener

public void init()

addMouseMotionListener(this);

setBackground(Color.red);

public void mouseDragged(MouseEvent me)

20JG5A0503 121 | P a g e
|| CSE R19 JAVA PROGRAMMING

Graphics g=getGraphics();

g.setColor(Color.white);

g.fillOval(me.getX(),me.getY(),10,10); // (x-position, y-postion, width,


height)

public void mouseMoved(MouseEvent me)

 HTML CODE FOR APPLET:

<html>

<applet code="Paintbrush.class" height=300 width=400>

</applet>

</html>

Input/output:

20JG5A0503 122 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 123 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 13(b)
write a JAVA program to display analog clock

using Applet.

AIM:
JAVA program to display analog clock using

Applet.

Source code:

import java.applet.Applet;

import java.awt.*;

import java.util.*;

public class clockdemo extends Applet {

@Override

public void init()

// Applet window size & color

this.setSize(new Dimension(800, 400));

new Thread() {

@Override

20JG5A0503 124 | P a g e
|| CSE R19 JAVA PROGRAMMING

public void run()

while (true) {

repaint();

delayAnimation();

}.start();

// Animating the applet

private void delayAnimation()

try {

// Animation delay is 1000 milliseconds

Thread.sleep(1000);

catch (InterruptedException e) {

e.printStackTrace();

20JG5A0503 125 | P a g e
|| CSE R19 JAVA PROGRAMMING

// Paint the applet

@Override

public void paint(Graphics g)

// Get the system time

Calendar time = Calendar.getInstance();

int hour = time.get(Calendar.HOUR_OF_DAY);

int minute = time.get(Calendar.MINUTE);

int second = time.get(Calendar.SECOND);

// 12 hour format

if (hour > 12) {

hour -= 12;

// Draw clock body center at (400, 200)

g.setColor(Color.black);

g.fillOval(300, 100, 200, 200);

20JG5A0503 126 | P a g e
|| CSE R19 JAVA PROGRAMMING

// Labeling

g.setColor(Color.pink);

g.drawString("12", 390, 120);

g.drawString("9", 310, 200);

g.drawString("6", 400, 290);

g.drawString("3", 480, 200);

// Declaring variables to be used

double angle;

int x, y;

// Second hand's angle in Radian

angle = Math.toRadians((15 - second) * 6);

// Position of the second hand

// with length 100 unit

x = (int)(Math.cos(angle) * 100);

y = (int)(Math.sin(angle) * 100);

// Red color second hand

g.setColor(Color.red);

20JG5A0503 127 | P a g e
|| CSE R19 JAVA PROGRAMMING

g.drawLine(400, 200, 400 + x, 200 - y);

// Minute hand's angle in Radian

angle = Math.toRadians((15 - minute) * 6);

// Position of the minute hand

// with length 80 unit

x = (int)(Math.cos(angle) * 80);

y = (int)(Math.sin(angle) * 80);

// blue color Minute hand

g.setColor(Color.blue);

g.drawLine(400, 200, 400 + x, 200 - y);

// Hour hand's angle in Radian

angle = Math.toRadians((15 - (hour * 5)) * 6);

// Position of the hour hand

// with length 50 unit

x = (int)(Math.cos(angle) * 50);

y = (int)(Math.sin(angle) * 50);

20JG5A0503 128 | P a g e
|| CSE R19 JAVA PROGRAMMING

// Black color hour hand

g.setColor(Color.green);

g.drawLine(400, 200, 400 + x, 200 - y);

 HTML CODE FOR APPLET:

<html>

<applet code="clockdemo.class" height=300 width=400>

</applet>

</html>

Input/output:

20JG5A0503 129 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 130 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 13(c)
Write a JAVA program to create different shapes

and fill colors using Applet.

AIM:

JAVA program to create different shapes and fill

colors using Applet.

Source code:

import java.awt.*;

import java.applet.*;

public class graphicsdemo extends Applet

20JG5A0503 131 | P a g e
|| CSE R19 JAVA PROGRAMMING

public void paint(Graphics g)

int x[]={10,220,220};

int y[]={400,400,520};

int n=3;

g.setColor(Color.green);

g.drawLine(10,30,200,30);

g.setColor(Color.blue);

g.drawRect(30,40,200,30);

g.setColor(Color.blue);

g.fillRect(50,80,200,30);

g.setColor(Color.orange);

g.drawRoundRect(70,120,200,30,20,20);

g.setColor(Color.orange);

g.fillRoundRect(90,160,200,30,20,20);

g.setColor(Color.blue);

g.drawOval(110,200,200,30);

g.setColor(Color.pink);

g.fillOval(130,240,40,40);

g.setColor(Color.yellow);

20JG5A0503 132 | P a g e
|| CSE R19 JAVA PROGRAMMING

g.drawArc(150,290,200,30,0,180);

g.setColor(Color.yellow);

g.fillArc(170,330,200,30,0,180);

g.setColor(Color.pink);

 HTML CODE FOR APPLET:

<html>

<applet code=" graphicsdemo class" height=300 width=400>

</applet>

</html>

Input/output:

20JG5A0503 133 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 134 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Event Handling)

Exercise – 14(a)
Write a JAVA program that display the x and y

position of the cursor movement using Mouse.

AIM:

JAVA program that display the x and y position of

the cursor movement using Mouse.

Source code:

import java.awt.*;

import java.awt.event.*;

import java.applet.Applet;

public class AppletMouse extends Applet implements MouseListener,


MouseMotionListener

int x, y;

String str="";

public void init()

20JG5A0503 135 | P a g e
|| CSE R19 JAVA PROGRAMMING

addMouseListener(this);

addMouseMotionListener(this);

public void mousePressed(MouseEvent e)

x = e.getX();

y = e.getY();

str = "Mouse Pressed";

repaint();

public void mouseReleased(MouseEvent e)

x = e.getX();

y = e.getY();

str = "Mouse Released";

repaint();

public void mouseClicked(MouseEvent e)

x = e.getX();

20JG5A0503 136 | P a g e
|| CSE R19 JAVA PROGRAMMING

y = e.getY();

str = "Mouse Clicked";

repaint();

public void mouseEntered(MouseEvent e)

x = e.getX();

y = e.getY();

str = "Mouse Entered";

repaint();

public void mouseExited(MouseEvent e)

x = e.getX();

y = e.getY();

str = "Mouse Exited";

repaint();

// override two abstract methods of


MouseMotionListener

public void mouseMoved(MouseEvent e)

20JG5A0503 137 | P a g e
|| CSE R19 JAVA PROGRAMMING

x = e.getX();

y = e.getY();

str = "Mouse Moved";

repaint();

public void mouseDragged(MouseEvent e)

x = e.getX();

y = e.getY();

str = "Mouse dragged";

repaint();

// called by repaint() method

public void paint(Graphics g)

g.setFont(new Font("Monospaced", Font.BOLD, 20));

g.fillOval(x, y, 10, 10);

//g.drawString(x + "," + y, x+10, y -10);

g.drawString(str, x+10, y+20);

showStatus(str + " at " + x + "," + y);

20JG5A0503 138 | P a g e
|| CSE R19 JAVA PROGRAMMING

HTML CODE FOR APPLET:

<html>

<applet code=" AppletMouse.class" height=300 width=400>

</applet>

</html>

Input/output:

20JG5A0503 139 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 140 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 141 | P a g e
|| CSE R19 JAVA PROGRAMMING

Exercise – 14(b)
Write a JAVA program that display the x and y

position of the cursor movement using Mouse.

AIM:

JAVA program that display the x and y position of

the cursor movement using Mouse.

Source code:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class KeyUpDown1 extends Applet implements KeyListener

String s1=" ";

int x,y;

public void init()

addKeyListener(this);

requestFocus();

public void keyPressed(KeyEvent ke)


20JG5A0503 142 | P a g e
|| CSE R19 JAVA PROGRAMMING

x=100;

y=200;

s1= "key pressed ";

repaint();

public void keyReleased(KeyEvent ke)

x=100;

y=400;

s1= "key Released ";

repaint();

public void keyTyped(KeyEvent ke)

s1=s1+ke.getKeyChar();

repaint();

public void paint(Graphics g)

g.drawString(s1,x,y);

20JG5A0503 143 | P a g e
|| CSE R19 JAVA PROGRAMMING

 HTML CODE FOR APPLET:

<html>

<applet code=" KeyUpDown1.class" height=300 width=400>

</applet>

</html>

Input/output:

20JG5A0503 144 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 145 | P a g e
|| CSE R19 JAVA PROGRAMMING

(STRINGS)

(Extra Programs-1)

Write a JAVA program to illustrate string handling

functions

AIM:

JAVA program to illustrate string handling

functions

Source code:

//String handling functions

import java.lang.*;

public class Str_Handle

public static void main(String args[])

//extracting characters from strings

String str="Hello,Hi";

System.out.println("Character at index5 is "+str.charAt(0));


//charAt()

char buf[]=new char[10-5];

20JG5A0503 146 | P a g e
|| CSE R19 JAVA PROGRAMMING

char[] characters=str.toCharArray(); //toCharArray()

System.out.println("toCharArray()");

for (char c : characters) {

System.out.println(c);

byte[] bs=str.getBytes(); //getBytes()

System.out.println("getBytes()");

for (byte b: bs) {

System.out.println(b);

//comparing strings

String s1="rohi";

String s2="anu";

String s3="anu";

String s4=new String("anu");

System.out.println("s1.equals(s2)::"+s1.equals(s2));
//equals()

System.out.println("s2.equals(s3)::"+s2.equals(s3));

System.out.println("s2==s3::"+s2==s3); //== operator

System.out.println("s2==s4::"+s2==s4);

20JG5A0503 147 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("s2.compareTo(s3)::"+s2.compareTo(s3));
//compareTo()

System.out.println("s1.compareTo(s2)::"+s1.compareTo(s2));

System.out.println("s2.compareTo(s1)::"+s2.compareTo(s1));

//modifying strings

System.out.println("s1.concat(s2)::"+s1.concat(s2));
//concat()

System.out.println("s1.replace('o','r')::"+s1.replace('o','r'));
//replace()

System.out.println("s1.substring(1,3)::"+s1.substring(1,3));
//substring()

//searching strings

String s5="deepu kadambari";

int first_i=s5.indexOf('d'); //indexOf()

System.out.println("First occurance:"+first_i);

int last_i=s5.lastIndexOf('d'); //lastIndexOf()

System.out.println("Last occurance:"+last_i);

Input/output:

20JG5A0503 148 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 149 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Extra Program-2)

Write a JAVA program to illustrate string builder

functions

AIM:

JAVA program to illustrate string builder functions

Source code:

import java.lang.Exception;

import java.util.*;

import java.util.concurrent.LinkedBlockingQueue;

public class Stringbuilder_prog{

public static void main(String[] argv)

throws Exception

// create a StringBuilder object

// with a String pass as parameter

StringBuilder str

= new StringBuilder("rohitha mapauna");

20JG5A0503 150 | P a g e
|| CSE R19 JAVA PROGRAMMING

// print string

System.out.println("String = "

+ str.toString());

// reverse the string

StringBuilder reverseStr = str.reverse();

// print string

System.out.println("Reverse String = "

+ reverseStr.toString

());

// Append ', '(44) to the String

str.appendCodePoint(44);

// Print the modified String

System.out.println("Modified StringBuilder = "

+ str);

// get capacity

int capacity = str.capacity();

20JG5A0503 151 | P a g e
|| CSE R19 JAVA PROGRAMMING

// print the result

System.out.println("StringBuilder = " + str);

System.out.println("Capacity of StringBuilder = "

+ capacity);

Input/output:

20JG5A0503 152 | P a g e
|| CSE R19 JAVA PROGRAMMING

(This usage)

(Extra Program-3(a))

Write a JAVA program to illustrate this

usage(current class instance)

AIM:

JAVA program to illustrate this usage

Source code:

import java.util.Scanner;

class this_currentclass_instance{

int id;

String name;

int marks;

this_currentclass_instance(int id,String name,int marks){

this.id=id;

this.name=name;

this.marks=marks;

void display(){

20JG5A0503 153 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println(name+", holding idno "+id+" got "+marks+"


marks");

class thisdemo1{

public static void main(String args[]){

Scanner s=new Scanner(System.in);

System.out.println("Enter the name of the student: ");

String name=s.nextLine();

System.out.println("Enter the student idno: ");

int id=s.nextInt();

System.out.println("Enter student marks: ");

int marks=s.nextInt();

this_currentclass_instance s1=new
this_currentclass_instance(id,name,marks);

Input/output:

20JG5A0503 154 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 155 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Extra Program-3(b))

Write a JAVA program to illustrate this

usage(invoke current class )

AIM:

JAVA program to illustrate this usage

Source code:

import java.util.Scanner;

class this_invokecurrent_class{

int id;

String name;

int marks;

this_invokecurrent_class(int idno,String s_name,int s_marks){

id=idno;

name=s_name;

marks=s_marks;

void show(){

System.out.println("\nThis show() is called by thisoperator");

Scanner s=new Scanner(System.in);

20JG5A0503 156 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("Enter the name of the student: ");

String name=s.nextLine();

System.out.println("Enter the student idno: ");

int id=s.nextInt();

System.out.println("Enter student marks: ");

int marks=s.nextInt();

System.out.println(name+", holding idno "+id+" got


"+marks+" marks");

void display(){

System.out.println(name+", holding idno "+id+" got "+marks+"


marks");

this.show();

class thisdemo2{

public static void main(String args[]){

Scanner s=new Scanner(System.in);

System.out.println("Enter the name of the student: ");

String name=s.nextLine();

System.out.println("Enter the student idno: ");

int id=s.nextInt();

20JG5A0503 157 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("Enter student marks: ");

int marks=s.nextInt();

this_invokecurrent_class s1=new
this_invokecurrent_class(id,name,marks);

s1.display();

Input/output:

20JG5A0503 158 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Extra Program-3(c))

Write a JAVA program to illustrate this

usage(current class Constructor )

AIM:

JAVA program to illustrate this usage

Source code:

import java.util.Scanner;

class this_currentclass_constructor{

int id;

String name;

int marks;

this_currentclass_constructor(){

System.out.println("\nThis is a constructor student");

Scanner s=new Scanner(System.in);

System.out.println("Enter the name of the student: ");

String name=s.nextLine();

System.out.println("Enter the student idno: ");

int id=s.nextInt();

System.out.println("Enter student marks: ");

20JG5A0503 159 | P a g e
|| CSE R19 JAVA PROGRAMMING

int marks=s.nextInt();

System.out.println(name+", holding idno "+id+" got "+marks+"


marks");

this_currentclass_constructor(int id,String name,int marks){

this();

System.out.println(name+", holding idno "+id+" got "+marks+"


marks");

class thisdemo3{

public static void main(String args[]){

System.out.println("This is a main student");

Scanner s=new Scanner(System.in);

System.out.println("Enter the name of the student: ");

String name=s.nextLine();

System.out.println("Enter the student idno: ");

int id=s.nextInt();

System.out.println("Enter student marks: ");

int marks=s.nextInt();

this_currentclass_constructor s1=new
this_currentclass_constructor(id,name,marks);

20JG5A0503 160 | P a g e
|| CSE R19 JAVA PROGRAMMING

Input/output:

20JG5A0503 161 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Jdbc connection)

(Extra Program-4)

Write a JAVA program to connect mysql

AIM:

JAVA program to connect mysql

Source code:

import java.sql.*;

public class FirstExample1 {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL =


"jdbc:mysql://localhost:3306/studentdetails";

// Database credentials

static final String USER = "root";

static final String PASS = "";

20JG5A0503 162 | P a g e
|| CSE R19 JAVA PROGRAMMING

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database...");

conn =
DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query

System.out.println("Creating statement...");

stmt = conn.createStatement();

String sql;

sql = "SELECT rollno,marks,name FROM student";

ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set

while(rs.next()){

//Retrieve by column name

20JG5A0503 163 | P a g e
|| CSE R19 JAVA PROGRAMMING

int rollno = rs.getInt("rollno");

int marks = rs.getInt("marks");

String name = rs.getString("name");

//Display values

System.out.print("ID: " + rollno);

System.out.print(",Name: " + name);

System.out.print(",marks: " + marks+"\n");

//STEP 6: Clean-up environment

rs.close();

stmt.close();

conn.close();

}catch(SQLException se){

//Handle errors for JDBC

se.printStackTrace();

}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

20JG5A0503 164 | P a g e
|| CSE R19 JAVA PROGRAMMING

//finally block used to close resources

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se2){

}// nothing we can do

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

}//end finally try

}//end try

System.out.println("Goodbye!");

}//end main

}//end FirstExample

Input/output:

20JG5A0503 165 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 166 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Extra Program-5)

Write a JAVA program to inserting the batch

process

AIM:

JAVA program to inserting the batch process

Source code:

import java.sql.BatchUpdateException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.util.Arrays;

import java.sql.*;

/**

* Insert Batch operation using PreparedStatement Interface

* @author Ramesh Fadatare

*/

20JG5A0503 167 | P a g e
|| CSE R19 JAVA PROGRAMMING

public class BatchInsert {

public static void main(String[] args) {

parameterizedBatchUpdate();

public static void printSQLException(SQLException ex) {

for (Throwable e: ex) {

if (e instanceof SQLException) {

e.printStackTrace(System.err);

System.err.println("SQLState: " + ((SQLException)


e).getSQLState());

System.err.println("Error Code: " + ((SQLException)


e).getErrorCode());

System.err.println("Message: " + e.getMessage());

Throwable t = ex.getCause();

while (t != null) {

System.out.println("Cause: " + t);

t = t.getCause();

20JG5A0503 168 | P a g e
|| CSE R19 JAVA PROGRAMMING

private static void parameterizedBatchUpdate() {

String INSERT_USERS_SQL = "INSERT INTO student" + "


( name, rollno,marks) VALUES " +

" (?, ?, ?);";

try (Connection connection = DriverManager

.getConnection("jdbc:mysql://localhost:3306/studentdetails",
"root", "");

// Step 2:Create a statement using connection object

PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_USERS_SQL)) {

connection.setAutoCommit(false);

System.out.println("The row 1 is inserting.......");

preparedStatement.setString(1, "Rohitha");

preparedStatement.setInt(2, 102);

preparedStatement.setInt(3, 96);

preparedStatement.addBatch();

int[] cou1=preparedStatement.executeBatch();;

20JG5A0503 169 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("The row 1 is inserted successfully and the


count is : ("+Arrays.toString(cou1)+")");

System.out.println("The row 2 is inserting.......");

preparedStatement.setString(1, "Rohitha");

preparedStatement.setInt(2, 102);

preparedStatement.setInt(3, 96);

preparedStatement.addBatch();

int[] cou2=preparedStatement.executeBatch();;

System.out.println("The row 2 is inserted successfully and the


count is : ("+Arrays.toString(cou2)+")");

System.out.println("The row 3 is inserting.......");

preparedStatement.setString(1, "Rohi");

preparedStatement.setInt(2, 103);

preparedStatement.setInt(3, 96);

preparedStatement.addBatch();

int[] cou3=preparedStatement.executeBatch();;

System.out.println("The row 3 is inserted successfully and the


count is : ("+Arrays.toString(cou3)+")");

System.out.println("The row 4 is inserting.......");

20JG5A0503 170 | P a g e
|| CSE R19 JAVA PROGRAMMING

preparedStatement.setString(1, "hitha");

preparedStatement.setInt(2, 104);

preparedStatement.setInt(3, 95);

preparedStatement.addBatch();

int[] cou4=preparedStatement.executeBatch();;

System.out.println("The row 4 is successfully completed and


the count is : ("+Arrays.toString(cou4)+")");

connection.commit();

connection.setAutoCommit(true);

} catch (BatchUpdateException batchUpdateException) {

printBatchUpdateException(batchUpdateException);

} catch (SQLException e) {

printSQLException(e);

public static void printBatchUpdateException(BatchUpdateException


b) {

System.err.println("----BatchUpdateException----");

System.err.println("SQLState: " + b.getSQLState());

System.err.println("Message: " + b.getMessage());

20JG5A0503 171 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.err.println("Vendor: " + b.getErrorCode());

System.err.print("Update counts: ");

int[] updateCounts = b.getUpdateCounts();

for (int i = 0; i < updateCounts.length; i++) {

System.err.print(updateCounts[i] + " ");

Input/output:

20JG5A0503 172 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 173 | P a g e
|| CSE R19 JAVA PROGRAMMING

(Extra Program-6)

Write a JAVA program for transaction

managemant

AIM:

JAVA program for transaction managemant

Source code:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Savepoint;

import java.sql.Statement;

public class Transaction_Management {

public static void main(String[] args) throws ClassNotFoundException


{

// TODO Auto-generated method stub

//Select Query to get the Data from employee_details table

String QUERY = "select * from student where rollno = 103";

20JG5A0503 174 | P a g e
|| CSE R19 JAVA PROGRAMMING

String QUERY1 = "select * from student where rollno = 101";

Boolean autoCommit;

String update_query = "update student set marks = 92 where


rollno=103";

String update_query1 = "update student set marks = 99 where


rollno=101";

try (Connection conn =


DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetai
ls", "root", ""))

Statement statemnt1=conn.createStatement();

ResultSet rs1 =null;

//Checking whether the SELECT query is executed


successfully or not

rs1 = statemnt1.executeQuery(QUERY);

//Executed the SELECT Query

System.out.println("Getting the data from student table");

displayData(rs1);

rs1 = statemnt1.executeQuery(QUERY1);

displayData(rs1);

//Set the autoCommit value of the connection to FALSE

20JG5A0503 175 | P a g e
|| CSE R19 JAVA PROGRAMMING

System.out.println("\nSetting the AutoCommit value as


FALSE");

conn.setAutoCommit(false);

autoCommit = conn.getAutoCommit();

System.out.println("\nAutoCommit value of the Connection =


"+ autoCommit);

//Creating Statement to execute the update query

statemnt1 = conn.createStatement();

System.out.println("\nExecuting Update query to update


marks of student = 103");

System.out.println("\nUpdate Query is " + update_query);

int return_rows = statemnt1.executeUpdate(update_query);

System.out.println("\nUpdated the data but didn't commit");

//Getting data after Updation

Connection conn1 =
DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetai
ls", "root", "");

System.out.println("\nOpening new connection");

System.out.println("rollno = 103 data");

Statement statement2 = conn1.createStatement();

ResultSet rs;

rs = statement2.executeQuery(QUERY);

20JG5A0503 176 | P a g e
|| CSE R19 JAVA PROGRAMMING

displayData(rs);

System.out.println("\nCommit has been done");

conn.commit();

Savepoint s1 = conn.setSavepoint();

System.out.println("\nSavePoint has been created");

System.out.println("Displaying data of rollno=103");

System.out.println("\nUsing The Second Connection");

rs = statement2.executeQuery(QUERY);

displayData(rs);

rs = statemnt1.executeQuery(QUERY);

//Rollback the transaction

System.out.println("Data of rollno =101");

rs1 = statemnt1.executeQuery(QUERY1);

displayData(rs1);

System.out.println("Updating the salary of rollno =101");

System.out.println("Update Query is " + update_query1);

statemnt1.executeUpdate(update_query1);

System.out.println("Data of rollno =101 but didn't commit");

rs1 = statemnt1.executeQuery(QUERY1);

statemnt1.executeUpdate(update_query1);

System.out.println("Data of rollno =101 but didn't commit");

20JG5A0503 177 | P a g e
|| CSE R19 JAVA PROGRAMMING

rs1 = statemnt1.executeQuery(QUERY1);

displayData(rs1);

System.out.println("\nRollback is done... so updated data


won't be reflected");

conn.rollback(s1);

System.out.println("Data of rollno =101 after Rollback till the


last savepoint");

rs1 = statemnt1.executeQuery(QUERY1);

displayData(rs1);

catch (SQLException e) {

e.printStackTrace();

public static void displayData(ResultSet rs1) throws SQLException

while(rs1.next())

int rollno = rs1.getInt("rollno");

20JG5A0503 178 | P a g e
|| CSE R19 JAVA PROGRAMMING

int marks = rs1.getInt("marks");

String name = rs1.getString("name");

System.out.print("ID: " + rollno);

System.out.print(",Name: " + name);

System.out.print(",marks: " + marks+"\n");

Input/output:

20JG5A0503 179 | P a g e
|| CSE R19 JAVA PROGRAMMING

20JG5A0503 180 | P a g e

You might also like