JAVA LAB MANUAL AIDS 2yr
JAVA LAB MANUAL AIDS 2yr
(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.
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.
23
c) Write a JAVA program for creation of Java Built-in Exceptions
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
}}
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
int a, b, 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)
r1 = ( - b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
else if(D == 0)
r1 = (-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
else
Output:
Enter a:2
Enter b:3
Enter c: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.
import java.io.*;
import java.util.*;
class Bikers
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)
if( S2>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S2);
if( S3>AvgSpeed)
if( S4>AvgSpeed)
if( S5>AvgSpeed)
Output:
56
75
67
78
65
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){
if (arr[mid] == key){
return mid;
}
if (arr[mid] > key){
}else{
return -1;
int last=arr.length-1;
if (result == -1)
else
Output:
b) Write a JAVA program to sort for an element in a given list of elements using bubblesort
//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};
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.
arr[k] = R[j];
j++;
}
k++;
}
j++;
k++;
}
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
class stringbufferdemo
sb1.delete(0,6);
System.out.println(sb1);
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
sb3.deleteCharAt(0);
System.out.println(sb3);
}
Output:
World
Some Content
hello World
class A
int l=10,b=20;
int area()
return l*b;
class methoddemo
A a1=new A();
int r=a1.area();
Out put
class Student4{
int id;
String name;
id = i;
name = n;
s1.display();
s2.display();
Out Put:
111 Karan
222 Aryan
Exercise - 4 (Methods)
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
int id;
String name;
Student(){
id = i;
name = n;
//object creation
Output:
Student Id : 0
Student Id : 10
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 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{
d.eat();
}}
Output:
weeping...
barking...
eating...
c) Write a java program for abstract class to find areas of different shapes
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
}
}
Output:
Hello
Exercise - 7 (Exception)
a) Write a JAVA program that describes exception handling mechanism
try{
a[5]=30/0;
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
OUT PUT:
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:
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
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)
{
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
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{
Out put:
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
}
}
}
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;
}
}
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)
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)
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[])
{
}
}
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.*;
@Override
public void init()
{
// Applet window size & color
try {
catch (InterruptedException e) {
e.printStackTrace();
}
}
// 12 hour format
if (hour > 12) {
hour -= 12;
}
// 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);
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);
(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:
(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.*;
int x=0;
int y=0;
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
// main method
public static void main(String[] args) {
new KeyListenerExample2();
}
}