0% found this document useful (0 votes)
52 views61 pages

JAVA LAB MANUAL AIDS 2yr

The document is a Java Lab Manual for the Department of Computer Science and Engineering for the academic year 2023-24, authored by D. Ritwik. It outlines program outcomes and specific outcomes related to engineering knowledge, problem-solving, and professional skills, followed by a detailed syllabus of Java programming exercises. The exercises cover various Java concepts including data types, control flow, object-oriented programming, exception handling, and threading.

Uploaded by

Ratna Kumari
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)
52 views61 pages

JAVA LAB MANUAL AIDS 2yr

The document is a Java Lab Manual for the Department of Computer Science and Engineering for the academic year 2023-24, authored by D. Ritwik. It outlines program outcomes and specific outcomes related to engineering knowledge, problem-solving, and professional skills, followed by a detailed syllabus of Java programming exercises. The exercises cover various Java concepts including data types, control flow, object-oriented programming, exception handling, and threading.

Uploaded by

Ratna Kumari
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/ 61

DEPARTMENT OF COMPUTER SCIENCE &ENGINEERING

AI andAI&DS IIYearI Semester

JAVA LAB MANUAL

(2023-24)

BY

D.RITWIK .ASS.PROFESSOR
COMPUTER SCIENCE ANDENGINEERING

ProgramOutcomes
PO1 Engineeringknowledge:Applytheknowledgeofmathematics,science,engineeringfundamentals,and
anengineeringspecialization tothesolutionofcomplexengineeringproblems.
PO2 Problemanalysis:Identify,formulate,reviewresearchliterature,andanalyzecomplexengineeringproblems
reachingsubstantiatedconclusions usingfirstprinciples ofmathematics,naturalsciences,and
engineeringsciences.
PO3 Design/developmentofsolutions:Designsolutionsforcomplexengineeringproblemsanddesignsystemcompo
nentsorprocessesthatmeetthespecifiedneedswithappropriateconsiderationforthe
publichealthandsafety,andthecultural,societal,andenvironmentalconsiderations.
PO4 Conductinvestigationsofcomplexproblems:Useresearch-
basedknowledgeandresearchmethodsincludingdesignofexperiments,analysisandinterpretationofdata,andsyn
thesisoftheinformationto
providevalidconclusions.
PO5 Moderntoolusage:Create,select,andapplyappropriatetechniques,resources,andmodernengineeringandITtoo
lsincludingpredictionandmodelingtocomplexengineeringactivitieswithan
understandingofthelimitations.
PO6 Theengineerandsociety:Applyreasoninginformedbythecontextualknowledgetoassesssocietal,health,safety,
legalandculturalissuesandtheconsequentresponsibilitiesrelevanttotheprofessional
engineeringpractice.
PO7 Environmentandsustainability:Understandthe impactof the
professionalengineeringsolutionsinsocietalandenvironmentalcontexts,anddemonstratetheknowledgeof,andn
eedforsustainable
development.
PO8 Ethics:Applyethicalprinciplesandcommittoprofessionalethicsandresponsibilitiesandnormsofthe
engineeringpractice.
PO9 Individualandteamwork:Functioneffectivelyasanindividual,andasamemberorleaderindiverse
teams,andinmultidisciplinarysettings.
O10 Communication:Communicateeffectivelyoncomplexengineeringactivitieswiththeengineeringcommunitya
ndwithsocietyatlarge,suchas, beingabletocomprehendandwriteeffectivereportsand
designdocumentation,makeeffectivepresentations,andgiveandreceiveclearinstructions.
PO11 Projectmanagementandfinance:Demonstrateknowledgeandunderstandingoftheengineeringand
managementprinciplesandapplythesetoone’sownwork,asamemberandleaderinateam,tomanageprojectsand
inmultidisciplinaryenvironments.
PO12 Life-longlearning:Recognizetheneedfor,andhavethepreparationandabilitytoengagein
independentandlife-longlearninginthebroadestcontextoftechnologicalchange.
ProgramSpecificOutcomes
PSO1 ProfessionalSkills:Theabilitytoresearch,understandandimplementcomputerprogramsintheareasrelatedtoalg
orithms,systemsoftware,multimedia,webdesign,bigdataanalytics,andnetworkingfor
efficientanalysisanddesignofcomputer-based systemsofvaryingcomplexity.
PSO2 Problem-
SolvingSkills:Theabilitytoapplystandardpracticesandstrategiesinsoftwareprojectdevelopmentusingopen-
endedprogrammingenvironmentstodeliveraqualityproductforbusiness
success.
PSO3 SuccessfulCareerandEntrepreneurship:Theabilitytoemploymoderncomputerlanguages,environments,an
dplatformsincreatinginnovativecareerpaths,tobeanentrepreneur,andazestfor
higherstudies.

JAVA LABS YLLABUS

Exp Division
ListofExperiments
.No ofExperiments
.
a) Write a JAVA program to display default value of all primitive data
1 type of JAVA
Exercise - 1
2 b)Write a java program that display the roots of a quadratic
(Basics) equation ax2+bx=0. Calculate the discriminate 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


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

a) Write a JAVA program to search for an element in a given list


4 Exercise-2
of elements using binary search mechanism.
(Operations,
Expressions, b) Write a JAVA program to sort for an element in a given list of
5
Control-flow, elements using bubble sort
Strings)
c)Write a JAVA program to sort for an element in a given list of elements
6 using merge sort.

d)Write a JAVA program using StringBuffer to delete, remove character.


7

a) Write a JAVA program to implement class mechanism.


8 Exercise - 3
Create a class, methods and invoke them inside main method.
(Class,
Objects) b) Write a JAVA program to implement constructor.
9

a) Write a JAVA program to implement constructor overloading.


10 Exercise - 4
(Methods)
11
b)Write a JAVA program implement method overloading.

a) Write a JAVA program to implement Single Inheritance


12 Exercise - 5
(Inheritance)
b)Write a JAVA program to implement multi level Inheritance
13 b

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


14
shapes

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


15 Exercise - 6
(Inheritance -
Continued b)Write a JAVA program to implement Interface. What kind of
16
Inheritance can be achived

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


17
(Exception)
b) Write a JAVA program Illustrating Multiple catch clauses
18

a) Write a JAVA program that implements Runtime polymorphism


19 Exercise – 8
(Runtime b) Write a Case study on run time polymorphism, inheritance that
20 Polymorphism implements in above problem
)

a) Write a JAVA program for creation of Illustrating throw


21 Exercise – 9
(User defined
Exception) b) Write a JAVA program for creation of Illustrating finally
22
24

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

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


24

a) Write a JAVA program that creates threads by extending


25 Exercise – 10 Thread class .First thread display “Good Morning “every 1 sec,
(Threads) the second thread displays “Hello “every 2 seconds and the third
display “Welcome” every 3 seconds ,(Repeat the same by
implementing Runnable)
b) a program illustrating isAlive and join ()

c) e a Program illustrating Daemon Threads.


26

a) Write a JAVA program Producer Consumer Problem


27 Exercise - 11
(Threads
continuity) b)Write a case study on thread Synchronization after solving the
28
above producer consumer problem

a) Write a JAVA program illustrate class path


29 Exercise – 12
(Packages) b) Write a case study on including in class path in your os environment
30
of your package.

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

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

public class Demo {

static boolean val1;

static double val2;

static float val3;

static int val4;


static long val5;

static String val6;

public static void main(String[] args) {

System.out.println("Default values. ... ");

System.out.println("Val1 = " + val1);

System.out.println("Val2 = " + val2);

System.out.println("Val3 = " + val3);

System.out.println("Val4 = " + val4);

System.out.println("Val5 = " + val5);


System.out.println("Val6 = " + val6)

}}

Output

Default values.....

Val1 = false

Val2 = 0.0

Val3 = 0.0

Val4 = 0

Val5 = 0

Val6 = null

b) Write a java program that display the roots of a quadratic equation ax 2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of
root.

import java.util.*;

class quadraticdemo

public static void main(String[] args)

int a, b, c;

double r1, r2, D;

Scanner s = new Scanner(System.in);

System.out.println("Given quadratic equation:ax^2 + bx + c");

System.out.print("Enter a:");

a = s.nextInt();

System.out.print("Enter b:");

b = s.nextInt();

System.out.print("Enter c:");
c = s.nextInt();

D = b * b - 4 * a * c;

if(D > 0)

System.out.println("Roots are real and unequal");

r1 = ( - b + Math.sqrt(D))/(2*a);

r2 = (-b - Math.sqrt(D))/(2*a);

System.out.println("First root is:"+r1);

System.out.println("Second root is:"+r2);

else if(D == 0)

System.out.println("Roots are real and equal");

r1 = (-b+Math.sqrt(D))/(2*a);

System.out.println("Root:"+r1);

else

System.out.println("Roots are imaginary");

Output:

Given quadratic equation:ax^2 + bx +c

Enter a:2

Enter b:3
Enter c:1

Roots are real and unequal

First root is:-0.5

Second root is:-1.0

c) 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.io.*;

import java.util.*;

class Bikers

static float S1,S2,S3,S4,S5;

static float AvgSpeed;

public static void main(String args[ ])

Scanner input = new Scanner(System.in);

System.out.println(" Enter Speed of five Bike Racer");

S1 = input.nextInt();

S2 = input.nextInt();

S3 = input.nextInt();

S4 = input.nextInt();

S5 = input.nextInt();

AvgSpeed=(S1+S2+S2+S3+S4+S5)/5;

if( S1>AvgSpeed)

System.out.println("The Speed of Qualifying Racer is"+S1);

if( S2>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S2);

if( S3>AvgSpeed)

System.out.println(" The Speed of Qualifying Racer is"+S3);

if( S4>AvgSpeed)

System.out.println(" The Speed of Qualifying Racer is"+S4);

if( S5>AvgSpeed)

System.out.println(" The Speed of Qualifying Racer is"+S5);

Output:

Enter the speed of Five Bike Racces

56

75

67

78

65

The Speed of the Qualifying Racer is 7

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.

class BinarySearchExample1{

public static int binarySearch(int arr[], int first, int last, int key){

if (last>=first){

int mid = first + (last - first)/2;

if (arr[mid] == key){

return mid;

}
if (arr[mid] > key){

return binarySearch(arr, first, mid-1, key);//search in left subarray

}else{

return binarySearch(arr, mid+1, last, key);//search in right subarray

return -1;

public static void main(String args[]){

int arr[] = {10,20,30,40,50};

int key = 30;

int last=arr.length-1;

int result = binarySearch(arr,0,last,key);

if (result == -1)

System.out.println("Element is not found!");

else

System.out.println("Element is found at index: "+result);

Output:

Element is found at index: 2

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

public class BubbleSortExample {


static void bubbleSort(int[] arr) {
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] + " ");
}
}
}

Output:
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
c) Write a JAVA program to sort for an element in a given list of elements using merge sort.

/* Java program for Merge Sort */


class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int [n1];
int R[] = new int [n2];

/*Copy data to temp arrays*/


for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarray array


int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{

arr[k] = R[j];
j++;
}
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy remaining elements of R[] if any */

while (j < n2)


{
arr[k] = R[j];

j++;
k++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;

// Sort first and second halves


sort(arr, l, m);
sort(arr , m+1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;

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


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

// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
Output
Given Array
12 11 13 5 6 7
Sorted array
5 6 7 11 12 13
d) Write a JAVA program using StringBuffer to delete, remove character.

class stringbufferdemo

public static void main(String[] args)

StringBuffer sb1 = new StringBuffer("Hello World");

sb1.delete(0,6);

System.out.println(sb1);

StringBuffer sb2 = new StringBuffer("Some Content");

System.out.println(sb2);

sb2.delete(0, sb2.length());

System.out.println(sb2);

StringBuffer sb3 = new StringBuffer("Hello World");

sb3.deleteCharAt(0);

System.out.println(sb3);

}
Output:

World

Some Content

hello World

Exercise - 3 (Class, Objects)

a) Write a JAVA program to implement class mechanism. Create a class, methods


and invoke them inside main method.

class A

int l=10,b=20;

int area()

return l*b;

class methoddemo

public static void main(String args[])

A a1=new A();

int r=a1.area();

System.out.println("The area is: "+r);

Out put

The area is:200

b) Write a JAVA program to implement constructor.


//Java Program to demonstrate the use of the parameterized constructor.

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

//method to display the values

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

//calling method to display the values of object

s1.display();

s2.display();

Out Put:

111 Karan

222 Aryan

Exercise - 4 (Methods)

a) Write a JAVA program to implement constructor overloading.


class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}

class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:
22
33

b) Write a JAVA program implement method overloading

public class Student {

//instance variables of the class

int id;

String name;

Student(){

System.out.println("this a default constructor");

Student(int i, String n){

id = i;
name = n;

public static void main(String[] args) {

//object creation

Student s = new Student();

System.out.println("\nDefault Constructor values: \n");

System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");

Student student = new Student(10, "David");

System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);

Output:

this a default constructor

Default Constructor values:

Student Id : 0

Student Name : null

Parameterized Constructor values:

Student Id : 10

Student Name : David

Exercise - 5 (Inheritance)
a) Write a JAVA program to implement Single Inheritance

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}

class BabyDog extends Dog{


void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
barking...
eating...

b) Write a JAVA program to implement multi level Inheritance

class Animal{
void eat(){System.out.println("eating...");}

}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{

public static void main(String args[]){


BabyDog d=new BabyDog();
d.weep();
d.bark();

d.eat();
}}
Output:
weeping...
barking...
eating...

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

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,
getShape() method
s.draw();
}
}
Out Put:

drawing circle
Exercise - 6 (Inheritance - Continued)
a) Write a JAVA program give example for “super” keyword.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}

}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Out Put:

black
white

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


achieved
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();

}
}
Output:
Hello
Exercise - 7 (Exception)
a) Write a JAVA program that describes exception handling mechanism

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

b) Write a JAVA program Illustrating Multiple catch clauses

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{

int a[]=new int[5];

a[5]=30/0;

catch(ArithmeticException e)

System.out.println("Arithmetic Exception occurs");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("ArrayIndexOutOfBounds Exception occurs");

catch(Exception e)

System.out.println("Parent Exception occurs");

System.out.println("rest of the code");


}

OUT PUT:

Arithmetic Exception occurs

rest of the code

Exercise – 8 (Runtime Polymorphism)

a) Write a JAVA program that implements Runtime polymorphism

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

b) Write a Case study on run time polymorphism, inheritance that implements in above
problem
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();

a2.eat();
a3.eat();
}
}
Output:
eating
eating fruits
drinking Milk
Exercise – 9 (User defined Exception)
(a) Write a JAVA program for creation of Illustrating throw

public class ThrowsDemo


{
static void throwMethod1() throws NullPointerException
{
System.out.println ("Inside throwMethod1");
throw new NullPointerException ("Throws_Demo1");
}
static void throwMethod2() throws ArithmeticException
{
System.out.println("Inside throwsMethod2");
throw new ArithmeticException("Throws_Demo2");
}
public static void main(String args[])
{
try
{
throwMethod1();
}
catch (NullPointerException exp)
{
System.out.println ("Exception is: " +exp);
}
try
{
throwMethod2();
}
catch(ArithmeticException ae)
{
System.out.println("Exception is: "+ae);
}
}
}
c) Write a JAVA program for creation of Java Built-in Exceptions

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

}
}
Output:
Can't divide a number by 0
(d)Write a JAVA program for creation of User Defined Exception
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;

}
}

OUT PUT:
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");
}

}
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();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
• Output:

• E:\javamani>java ThreadDemo
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
hello
welcome
good morning

(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)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{

MyThread t1=new MyThread();


MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
out Put:
r1
true
true
r1
r2
r2

(c) Write a Program illustrating Daemon Threads

public class DaemonDemo1 extends Thread


{

public DaemonDemo1(String name1)


{
super(name1);
}
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println(getName() + " is Daemon thread");
}
else
{
System.out.println(getName() + " is User thread");
}
}
public static void main(String[] args)
{
DaemonDemo1 D1 = new DaemonDemo1("D1");
DaemonDemo1 D2 = new DaemonDemo1("D2");
DaemonDemo1 D3 = new DaemonDemo1("D3");
D1.setDaemon(true);
D1.start();
D2.start();
D3.setDaemon(true);
D3.start();
}
}

Out put:

Exercise - 11 (Threads continuity)


(a) Write a JAVA program Producer Consumer Problem

public class ProducerConsumerTest {

public static void main(String[] args) {


CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();

c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;

public synchronized int get() {


while (available == false) {
try {
wait();
} catch (InterruptedException e) {}

}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {

while (available == true) {


try {
wait();
} catch (InterruptedException e) { }
}

contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;

public Consumer(CubbyHole c, int number) {


cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);

}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);

try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }

}
}
}
Result
The above code sample will produce the following result.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6

Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

(b)Write a case study on thread Synchronization after solving the above producer
consumer problem
public class ProducerConsumer
{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Shop
{
private int materials;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{

try
{
wait();

}
catch (InterruptedException ie)
{
}
}
available = false;
notifyAll();
return materials;
}

public synchronized void put(int value)


{
while (available == true)
{
try
{
wait();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
materials = value;
available = true;
notifyAll();
}

}
class Consumer extends Thread
{
private Shop Shop;
private int number;
public Consumer(Shop c, int number)

{
Shop = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value " + this.number+ " got: " + value);
}
}
}
class Producer extends Thread
{
private Shop Shop;
private int number;
public Producer(Shop c, int number)
{
Shop = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.number+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
Exercise – 12 (Packages)

(a) Write a JAVA program illustrate class path


.
// If the following code is run when the CLASSPATH is not

// set, it will throw the above error.

// If it is set, we get the desired result

import java.io.*;

class GFG {
public static void main(String[] args)
{
// prints GeeksForGeeks to the console
System.out.println("GeekForGeeks!");
}
}
Output

GeekForGeeks!

Exercise - 13 (Applet)

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

import java.awt.Frame;

import java.awt.Label;
import java.awt.event.*;

import java.awt.Graphics;

import java.awt.Color;
public class MouseMotionListenerDemoC extends Frame implements
MouseMotionListener
{
Label l1;
MouseMotionListenerDemoC()
{

addMouseMotionListener(this);
l1=new Label("Mouse not found yet....Get the mouse on to the frame!!!");
l1.setBounds(20,50,500,50);
add(l1);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public static void main(String a[])
{

MouseMotionListenerDemoC mmldc=new MouseMotionListenerDemoC();


}
public void mouseDragged(MouseEvent me)
{
l1.setText("Mouse Dragged"+me.getX()+" , "+me.getY());
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(me.getX(),me.getY(),20,20);
}
public void mouseMoved(MouseEvent me)
{
l1.setText("Mouse Moved"+me.getX()+" , "+me.getY());
//Graphics g=getGraphics();
//g.setColor(Color.green);
//g.fillOval(me.getX(),me.getY(),20,20);

}
}
OUT PUT:
(b)Write a JAVA program to display analog clock using Applet
// Java program to illustrate
// analog clock using Applets

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

public class analogClock extends Applet {

@Override
public void init()
{
// Applet window size & color

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


setBackground(new Color(50, 50, 50));
new Thread() {
@Override
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();
}
}

// 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.white);
g.fillOval(300, 100, 200, 200);

// Labeling
g.setColor(Color.black);
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);
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);

// Black color hour hand


g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}

(c)Write a JAVA program to create different shapes and fill colors using Applet.
/*Java Program to Create and Fill Shapes using Applet*/
import java.applet.*;
import java.awt.*;
public class Shapes extends Applet
{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
}
//Function to draw and fill shapes
public void paint(Graphics g)
{
//Draw a square
g.setColor(Color.black);
g.drawString("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
//Draw a pentagon
g.setColor(Color.black);
g.drawString("Pentagon",225,200);
x=new int[]{200,250,300,300,250,200};
y=new int[]{100,50,100,150,150,100};
g.drawPolygon(x,y,6);
g.setColor(Color.yellow);
g.fillPolygon(x,y,6);
//Draw a circle
g.setColor(Color.black);
g.drawString("Circle",400,200);
g.drawOval(350,50,125,125);
g.setColor(Color.yellow);
g.fillOval(350,50,125,125);
//Draw an oval
g.setColor(Color.black);
g.drawString("Oval",100,380);
g.drawOval(50,250,150,100);
g.setColor(Color.yellow);
g.fillOval(50,250,150,100);
//Draw a rectangle
g.setColor(Color.black);
g.drawString("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
//Draw a triangle
g.setColor(Color.black);
g.drawString("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
g.drawPolygon(x,y,3);
g.setColor(Color.yellow);
g.fillPolygon(x,y,3);
}
}
/*
<applet code = Shapes.class width=600 height=600>
</applet>
*/

OUT PUT:

Exercise - 14 (Event Handling)

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

import java.applet.*;

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

public class mouseevent2 extends Frame


{

int x=0;
int y=0;

public void init()


{

addMouseListener(new mymouselistener());
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g)
{
g.drawLine(x,y,x,y);
g.drawString(x + ","+ y, x,y);
}
public class mymouselistener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
repaint();
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);

}
}
public static void main(String p[])
{
mouseevent2 me2 = new mouseevent2();
me2.setSize(250, 250);
me2.setVisible(true);
me2.init();
}

Out Put:
(b)Write a JAVA program that identifies key-up key-down event user entering text in
Applet.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample2 extends Frame implements KeyListener {
// object of Label and TextArea
Label l;
TextArea area;

// class constructor
KeyListenerExample2() {
// creating the label
l = new Label();
// setting the location of label

l.setBounds (20, 50, 200, 20);


// creating the text area
area = new TextArea();
// setting location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to the text area
area.addKeyListener(this);
// adding label and text area to frame
add(l);
add(area);
// setting size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// even if we do not define the interface methods, we need to override them
public void keyPressed(KeyEvent e) {}
// overriding the keyReleased() method of KeyListener interface
public void keyReleased (KeyEvent e) {
// defining a string which is fetched by the getText() method of TextArea class
String text = area.getText();
// splitting the string in words
String words[] = text.split ("\\s");
// printing the number of words and characters of the string

l.setText ("Words: " + words.length + " Characters:" + text.length());


}
public void keyTyped(KeyEvent e) {}

// main method
public static void main(String[] args) {
new KeyListenerExample2();
}
}

You might also like