0 ratings 0% found this document useful (0 votes) 6 views 27 pages Java Lab Manual
The document is a lab manual for object-oriented programming in Java, containing various example programs. It covers fundamental concepts such as data types, string operations, inheritance, polymorphism, and exception handling. Each section includes code snippets and expected outputs for practical understanding.
AI-enhanced title and description
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Java lab manual For Later
Appendix A
OBJECT-ORIENTED PROGRAMMING LAB
LAB MANUAL
1, Java program to display “Hello World” and display the size of all the data types,
class Size Of DataTypes {
public static void main(String[] args) {
[Link](’Hello World”);
[Link](’[Link].\t_ Data Type\t Size”);
[Link](“I\t\t Byte\t\t\t" + [Link]!
[Link] printIn(“2\t\t_ Short\\t\t” + Short.S1Z
y
[Link] printin(“3\\t_Integer\t\t” + [Link]);
+ [Link]);
[Link](“S\\t Long\t\t\t” + Long. SIZE),
[Link](“6\t\t Double\t\t” + [Link]);
[Link](“4\\t_ Float\
System.out_printin(*7\\t, Character\\t" + Character. SIZE);
'
OUTPUT:
Hello World
Byte
Short
Integer
Float
Long
Double
aawa wn
Character__ Object Aeiented Programming Using [Av 4
tocal sad and global variables,
2. Java program to implement the uw! ge of static, Ie
State Global vanable ouminstances
private static int numinstances ~ 0,
protected static int getCount() |
return numinstances,
private stane vord addinstancet) |
numinstances* +,
InstaneeCountert ) |
InstanceCounter addInstance(),
)
public state void main(String[] arguments) |
Local vanable pi
float pim2278;
System.out_.pnintin( "Value of Pi =" + pis
System. out printin(’Starting with * + InstanceCounter getCountQ) +" instances”)
for (inti = 0;1< 5, +71) }
new InstanceCounter(};
System,out printin(“Created * > [Link]()
OUTPUT:
Value of Pi = 3.142857
Staring with O instances
Created $ instances,
-LAB Manual
appendix:
ee 175
3. Java program to implement string operations string length, string concatenat
substring °
L
class StringOperations {
public static void main(String{] args) {
String firstname="Sachin";
String middlename="" Ramesh”;
String lastname=" Tendulkar”;
String name=[Link](middlename).concat(lastname);
[Link]. printIn(“Name is: * + name);
[Link](“Lenth of name is: * + [Link]);
[Link](“substing of name is: * + [Link](7,13));
OUTPUT:
Name is: Sachin Ramesh Tendulkar
Lenth of name is: 23
substing of name is: Ramesh
Java program to find the maximum of three numbers
b
import [Link],
class MaxOfThreeNumbers {
public static void main(String[] args) {
int a, b, c, largest, temp;
Scanner sc = new Scanner([Link]);
[Link](“Enter the first number:");
a= [Link]();
[Link](“Enter the second number:");
= [Link]();
[Link](“Enter the third number:”);
c= [Link]();
‘comparing a and b and storing the largest number in a temp variable+8 Object-Oriented Progeamming Using av,
By
temp abby
comparing the temp variable with © and storing the result in the vartabl
largest: e>temp2ertemp;
[Link]’ The largest number iss"! largest);
}
OUTPUT:
Enter the first number
12
Enter the second number:
v7
Enter the third number:
1s
The largest number is; 47
Java program to check whether the number is odd or even,
ne
import [Link]. S
public class EvenOdd {
public static void main(String[] args) {
ner reader = new Seanner([Link]);
[Link](Enter a number:
intnum lernextint();
if{num % 2 == 0)
[Link] printin(num + * is even");
else
[Link](num + * is odd”);
Enter a number: 5
Sis oddLAT Manual
pa ey
fe ill sefault ond parameter leed constructors
wvautil Scant ——
6
[impor
: ——
class Box |
double width;
double height,
double depth;
Bot) |
width = 12.7d;
height = 15.04;
depth = 5.6d;
}
Box(double w, double h, double d) {
width = wy
height ~ h;
depth = d;
4
double volume() {
retum width * height * depth:
)
,
'
class Main {
public static void main(String{] args) |
Box Box! = new Box();
Box Box2 = new Box(4.7d, 8.5d, 6.34);
double vol:
// get volume of first box
vol = Box!.volume();
[Link] printin(“Volume of Box!" + vol);
// get volume of second box
vol = [Link].
[Link]. printin(“Volume of Box2: * + vol);
OUTPUT:
Volume of Box!: 1066.5
Volume of Box2: 251.685178 Object-Oriented Programming Using jay,
7, Java program to implement an array of ¢
import [Link] Scanner;
class Car {
public String name;
public int miles;
public Car(String name, int miles) {
[Link] = name;
this. miles = miles;
public void printDetails() {
[Link](name+” - “+miles);
'
class Main {
public static void main(String{] args) {
Car cars[] = ¢
new Car(“*Tesla”, 142000),
new Car(“BMW”, 485000),
new Car(“*Tata”, 564000),
new Car(“Ford”, 580000)
for(Car car: cars)
car printDetails();
Tesla - 142000
BMW - 485000
Tata - 564000
Ford ~ 580000appendix-LAB Manual 179
g. Java program to implement Single Inheritance
import [Link].S
nner,
Base cl:
ss/Super class
class Bicycle {
public int gear;
public int speed;
public Bicycle(int gear, int speed)
{
[Link] = gear;
[Link] = speed;
}
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
public String toString()
{
return (“No of gears are“ + gear + “\n”
+ “speed of bicycle is * + speed);
// derived class/sub class
class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int gear, int speed,
int startHeight)Object-Oriented Programming Using JAVA
a
superi gear, speed):
180
seatHeight = startHeight:
public void setHeight(int newValue)
\
seatHcight ~ newValue;
}
public String toString() *
return ([Link]() + “\nseat height is
+ seatHeight):
}
class Main {
public static void main(String] args) {
MountainBike mb = new MountainBike(3, 100, 25);
[Link]([Link]());
OUTPUT:
No of gears are 3
speed of bicycle is 100
seat height is 25
9. Java program to implement Multiple Inheritance using Interface
interface Character {
void attack();
}
interface Weapon {
void use);appendis-LAB Manual
i ——————§
ee
}
class Warrior implements Character, Weapon {
public void attack() {
[Link](’ Warrior attacks with
}
a sword."),
public void use() {
‘System. out printIn(*Warrior uses a sword.”
}
}
class Mage implements Character, Weapon {
public void attack() {
[Link] printin(*Mage attacks with a wand,");
'
public void use() {
[Link](“Mage uses a wand.”);
}
}
class Main {
public static void main(String[]) args) {
Warrior warrior = new Warrior():
Mage mage = new Mage();
warriorattack();
[Link]();
[Link]();
[Link]();
}
}
a
OUTPUT:
Warrior attacks with a sword.
Warrior uses a sword
Mage attacks with a wand.
Mage uses a wand,182 Object-Oriented Programming Using JAVA
10. Java program to implement an applet
‘SumNumslInteractive. java
Import [Link]. Applet;
import [Link].*;
public class SumNumsinteractive extends Applet {
TextField textl, text2;
Public void init)
1
text] = new TextField(10);
text2 = new TextField(10);
text setText(“0");
[Link](“0");
add(text!);
add(text
}
public void paint(Graphies g) {
int num! = 0;
int num2 = 0;
int sum;
String s1, s2, $3;
[Link](“Input a number in each box “, 10, 50);
uy t
sl = text! getText();
num! = [Link](s1);
$2 = [Link]();
num2 = [Link](s2);
}
catch(Exception e1)
sum = numl + num2;
UM IS
String str = “THE $ “+ [Link]);,
tiv LAB Manual
anne’ ei — -
Gousting StIOO2S
public boolean action(Event ev, Object obj)
repaint);
return true:
{
OUTPUT:
Se
"Ele GRR Yew Search Go Bookmart Tasks tp
ee eo
"Ai rene sd neescaoe A Search 9) Seep tomas
Sum of Numbers
Input a number in each bor
Il. Java program to demonstrate a division by zero exception
import [Link]. Scanner,
public class Division By _Zero_Exception {
public static void main(String{] args) {
try!
int numberl, number2, output
Scanner se=new Seanner([Link]);184
System. out print("Enter first number: “):
number! =[Link]();
stem. out print(“Enter second number : “)-
number2=[Link],
output=numberl /number2;
[Link](“Result:”+output):
}
catch(ArithmeticException ¢) {
[Link](“Error:”*+[Link]());
[Link](“Error:
te):
i
[Link](”
End of Program...
Lt
Output
Enter first number : 20
Enter second number : 10
Result:2
.oEnd of Program...
Output 2
Enter first number : 25
Enter second number : 0
Error:/ by zero
[Link] xception: | by zero
End of Program...appetiLAD Mant
vo. Java program to add two integers and Ovo Hoat numb:
‘Jee supplied give a default value to calculate the sum. Use
public class MethodOverload |
Method to add two integers
public int add(int a, int) {
return a + b;
/ Method to add pvo float numbers
public float addi float a, float b) {
retum a+ b;
/ Method to add two integers with default values
public int add() {
return add(5, 10): 4 default values
// Method to add two float numbers with default values
Public float add(float a) {
retum add(a, 2.58); /default value
}
Public static void main(String{] args) {
Scanner scanner = new Scanner([Link]);
MethodOverload calculator = new MethodOverload();
System. out printin(“Enter two integers (separated by space)
(or press Emter for default):");
String intInput = [Link]():
tf (intinput isEmpty) {
a a
185
$$$
ers, When no arguments
method overloading,186 Object-Oriented Programming Using JAVA
System-out prin iat™Sum of delaultmtcgers: Teateutator addy,
J else {
String[] intValues = [Link]’ “);
int a = Integer parselni(intValues[O));
int b = Integer. parse! nt(intValues| 1);
[Link] printin(“Sum of integers: * + [Link](a, b));
)
[Link] printin(’ Enter two float numbers (separated by space)
(or press Enter for defaul
[Link]();
String floatinput = sc
if ([Link]()) {
[Link] printin(*Sum of default floats: * + [Link](1 54);
} else {
String[] floatValues = [Link](* ");
float x = [Link] loat(floatValues[0});
float y = [Link] loat(floatValues[ 1]);
[Link](“Sum of floats: “ + [Link](x, y));
}
[Link]();
}
}
OUTPUT
Qutput: Wher cI values
Enter two integers (separated by space) (or press Enter for default):
15 25
Sum of integers: 40
Enter two float numbers (separated by space) (or press Enter for default):
63.2 56.1
Sum of floats: 119.3>
Lic LAB Manual
yn!
Quint When user is necentertng value snd press enters
sinter Wve integers (OF press Hnter For detinult
jun of default integers: 1S
Enter two float numbers (or press Enter for default)
sum of default oats: 4.0
Le
ji Java program that demonstrates run-time polymorphism,
class Employee {
// Method to be overridden
public void work() |
[Link] printn(“Employee is working”);
class Developer extends Employee {
1 Overriding the work method
@Overnide
public void work() {
[Link] printin(“Developer is writing code");
class Manager extends Employee {
1/ Overriding the work method
(Override
public void work() {
[Link] printing’ Manager 1s managing, the team");188 Object Odiented Programening Using JAVA
class Designer extends Employee
Overriding the work method
wOvernde
public vod work) |
[Link] printin(’ Designer is ercating designs”).
wblic class RunTimePolymorphism {
jymorp!
Public static void main(String|] args) {
System [Link](Demo for Runtime Polymorphism”);
[Link] printings —
7 Employee reference but Developer object
Employee emp = new Developer();
[Link]();
1/ Employee reference but Manager object
emp = new Manager():
[Link]();
7 Employee reference but Designer object
emp = new Designer();
[Link]();
4 Employee reference and Employee object
emp = new Employee();
[Link](Q):>
appendix-LAB Manual ae
OUTPUT
Demo for Runtime Polymorphism
Developer is writing code
Manager is managing the team
Designer is creating designs
Employee is working
14. Java program to catch negative array size Exception. This exception is caused
when the array is initialized to negat
import jav
public class Negative _array_Exception {
public static void main(String{] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter the size of the array: “);
int size = [Link]();
uy i
Attempt to create an array with the specified size
int{] array = new int(size];
[Link](“Array of size “ + size +“ created successfully.”);
catch (| Negative ArraySizeException et
[Link](“Error: Array size cannot be negative.");
;
catch (InputMismatchException e) {
[Link] printin(“Error: Invalid input. Please enter a valid integer.”
[Link](); // Clear the invalid input
finally §
[Link]();
}
[Link](*----END OF THE PROGRAM--190 Object-Oriented Programming Using JAVA
C— OUTPUT: |
ive interes
Enter the size of the array: 10
Array of size 10 created successfully.
END OF THE PROGRAM.—-
o 4 vee
Enter the size of the array: -6
Error: Array size cannot be negative
——END OF THE PROGRAM——-
oO it for of tha:
Enter the size of the array: C
Exception in thread “main” [Link].[nputMismatchException
at [Link]/[Link] [Link]([Link])
at java base java
[Link]([Link]: 1594)
at java. base/[Link] [Link]([Link])
at java. base/[Link](Scanner,java:2212)
at Book_Java_Lab/LabPrograms.Negative_array_Exception.main(Negative_array
Exception java:11)
1S. Java program to handle null pointer exception and use the “finally” method to
display a message to the user,
import [Link].*;
public class NullPointer Exception {
public static void main(String{] args) {
Scanner scanner = new Scanner([Link]);we
andi
LAB Manual
191
[Link](“Enter a string: “);
String input = [Link]();
try {
if (inpuLisEmpty()) {
input = null;
[Link](“Length of the string: “ + [Link]());
}
catch (NullPointerException e) {
[Link](“A null pointer exception occurred.”);
1
finally {
[Link] printIn(*——END OF PROGRAM");
[Link]();
OUTPUT
Qutput 1: Input is entered by user
Enter a string: Java World
Length of the string: 10
— END OF PROGRAM—
Output 1: No Input
Enter a string:
A null pointer exception occurred,
END OF PROGRAMetl packages.
de ‘sre folder in the workt
Square java’, “Triangle j
project
Step 1: Create a package "
Step 2: loside ‘shape’ create three classes ‘Circle jav
lass file ‘CustomPack. java
e main cl
Step 3: Outside the “shape* packayge er
.
Step 42 Run the ‘CustomPack ja
Cirelejava
package shape:
public class Circle |
private double radi
public Cirele(double r) {
radius=r;
}
public double area() {
return (3,14 *radius*radius);
‘[Link]
package shape;
public class Square {
private int side;
public Square(int s) {
side=s;
}
public int area() {
retum (side*side);>
agpcodin LAB Manual
fe
[Link]
package shape;
public class Triangle {
private int sidel ,side2,side3;
public Triangle(int sJ int «2,int 93) 4
sidel=s],
side2=s2;
side3=s3;,
1
public double areaf) {
double 5=(side | +side2+ side3)/2;
double a= Math sqn((s-side | )+(s-side2)+(s-side3));,
return a;
193
[Link]
a
package LabPrograms;
import shape.*;
import [Link].*;
public class CustomPack {
public static void main(String[] args) {
‘Scanner sc=new Scanner([Link]);
System [Link](“Enter The side of the Square
int s=[Link]),
Square sq=new Square(s);
[Link](“Area of Square is" + sq areal )),
System [Link](“Enter The radius of the Circle
double r=se nextDoublet),
oY
“y194 Object-Oriented Programming Using JAVA
Cirele ci=new Circle(s).
[Link](“Area of Circle ts ~~ [Link]()):
[Link] printin(“Enter The Sides of the Triangle :
int sI=[Link]();
int s2=[Link]();
int s3=[Link]();
shape Triangle t-new shape. Triangle(s!.s2,s3):
+ LareaQ):
[Link](“Area of Triangle
OUTPUT
Enter the side of the Square: 7
Area of Square is 49
Enter the radius of the Circle: 6
Area of Circle is 153.86
Enter The Sides of the Triangle:
6
5
8
Area of Triangle is 2.8284271247461903Manual
a ofA
Java program Co check whether a number is palindrome or not
v, -
import [Link]. Seanner,
ass PalindromeChecker {
public ef
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter a number: “);
int number = [Link]();
int originalNumber = number;
int reversedNumber = 0;
while (number = 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
if (originalNumber == reversedNumber) {
[Link](originalNumber + * is a palindrome.”);
} else {
[Link]. printIn(originalNumber +
\
[Link]();
}
a
js not a palindrome.”);eT ss—S
an Object-Oriented Programming, Using JAVA.
Qutpuc
Enter a number: 78524
78524 is not a palindrome
Outpur2;
Enter a number: 9669
9669 is a palindrome.
Java program to find the factorial of a list of numbers reading input as command
line argument.
import java. math BigInteger,
public class FactorialDemo {
public static void main(String[] args) {
for (String arg : args) {
try {
int number = [Link](arg);
[Link] printIn(“Factorial of “ + number + “=
“+ factorial(number));
} catch (NumberFormatException e) {
[Link](arg +“ is nota valid number.”);
}
private static BigInteger factorial(int number) {
BigInteger result = [Link]|
for (int i = 2; i <= number; i++) {
result ~ result. muliply([Link](i));-
gpottLAB Manual 197
an
retum result;
el
Eclipse Ul
pen Run => Run Configurations,
* Click on ‘Arguments’ tab.
+ Inside “Program Arguments” enter list of numbers one by one.
Finally click on *Run’ to sce the output.
OUTPUT
Factorial of 5 = 120
Factorial of 4 = 24
Factorial of 7 = 5040,
._ Java program to display all prime number
import [Link]. Scanner;
public
Ts between two limits,
ss PrimeNumbers {
Public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
System. [Link](“Enter the lower limit:
int lowerLimit = [Link]();
[Link](*Enter the upper limit: “);
int upperLimit = [Link]();
[Link] printin¢“Primenumbersbetween" + lowerLimit and” ++ upperLimit +
for (int num = lowerLimit; num <= upperLimit, num++) {
if (isPrime(num)) {
[Link](num + *")198 Object-Oriented Programming Using FAVA
public static boolean isPrime(int number) §
if (number Wt
retum false:
}
for (int i = 2; 1 <= [Link](number); i++) {
if (number % i = 0) |
retum false:
)
}
retum true;
OUTPUT
Enter the lower limit: 12
Enter the upper limit; 40
Prime numbers between 12 and 40 are:
13.17 19 23 29 3137
20. Java program to create a thread using Runnable Interface.
class MyThread implements Runnable {
private String threadName;
public MyThread(String threadName) {
[Link] = threadName;
}
@Override
public void run) {
[Link](threadName = ~ started.”);
for (int i = 0;1< 5; i++) |
[Link](threadName + “: * + i);
yt
Thread. sleep( 1000);
} catch (InterruptedException e) |
4 Sleep for 1 second
[Link](threadName + * interrupted.”);
aeenais LAD Manual
a
[Link](threadName + “ finished,”),
ThreadRunnable {
static void main(String] args) {
1 Create two threads
MyThread thread! = new MyThread(“Thread-1");
MyThread thread2 = new MyThread(“Thread-2");
1 Create Thread objects and pass the Runnable instances
Thread tl = new Thread(thread!);
Thread t2 = new Thread(thread2);
WStart the threads
tL start();
{2,start();
}
OUTPUT
Thread-2 started.
Thread-2: 0
Thread-1 started.
Thread-!: 0
Thread-1: 1
Thread-2: 2
Thread-1: 2
Thread-2: 3
Thread-1: 3
Thread-2: 4
Thread-1: 4
Thread-2 finished.
Thre ished.