JAVA PROGRAMMING
Lab Practicals – All 21 Programs
Prepared by: Tanushree Paul
[Link]. Computer Science – 4th Semester | Java OOP Lab
Each program uses clean, purpose-named classes — logic and demonstration code are separated wherever the concept
calls for it.
Contents
0 Command-line argument summation
1 CommandLineSum
0 Factorial of a number (recursion)
2 FactorialCalculator
0 Dynamically sized single-dimensional array
3 DynamicArrayDemo
0 2-D array traversal using .length
4 MatrixLengthDemo
0 Decimal to Binary conversion
5 DecimalToBinaryConverter
0 Prime number check (keyboard input)
6 PrimeChecker
0 Interactive N-integer sum + String/StringBuffer methods
7 InteractiveSum, StringBufferDemo
0 Distance class – objects and the 'this' keyword
8 Distance, DistanceDemo
0 Distance class – constructors, reference vs. clone
9 Distance, DistanceCloneDemo
1 Method overloading with automatic type promotion
0 TypePromotionDemo
1 Access specifiers, pass-by-value vs. reference, final
1 AccessDemo, AccessSpecifierDemo
1 Static methods and varargs
2 VarargsDemo
1 Autoboxing and unboxing
3 BoxingUnboxingDemo
1 Multi-file program – input in one file, output in another
4 MessageDisplay, MessageApp
1 Multilevel package with a Fibonacci generator
5 Fibonacci, FibonacciApp
1 Protection levels across classes/packages
6 BaseClass, SamePackageClass, DiffPackageSubclass, ProtectionDemo
Java Practicals – Tanushree Paul Page 1
1 ArithmeticException – divide by zero
7 DivideByZeroDemo
1 Nested try blocks and catch ordering
8 NestedTryDemo
1 User-defined custom exception
9 InsufficientFundsException, BankAccount, CustomExceptionDemo
2 Thread priority demonstration
0 PriorityThread, ThreadPriorityDemo
2 Producer-Consumer with synchronization
1 SharedBuffer, Producer, Consumer, ProducerConsumerDemo
Java Practicals – Tanushree Paul Page 2
01 Command-line argument summation
Class: CommandLineSum — single utility class (no split needed).
public class CommandLineSum {
public static void main(String[] args) {
int sum = 0;
for (String arg : args) {
sum += [Link](arg);
}
[Link]("Sum = " + sum);
}
}
SAMPLE OUTPUT
$ javac [Link]
$ java CommandLineSum 10 20 30 40
Sum = 100
02 Factorial of a number (recursion)
Class: FactorialCalculator — single utility class.
public class FactorialCalculator {
static long factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
int n = 6;
[Link]("Factorial of " + n + " = " + factorial(n));
}
}
SAMPLE OUTPUT
Factorial of 6 = 720
03 Dynamically sized single-dimensional array
Class: DynamicArrayDemo — single utility class.
Java Practicals – Tanushree Paul Page 3
import [Link];
public class DynamicArrayDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter size of array: ");
int n = [Link]();
int[] arr = new int[n]; // dynamic allocation
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Array elements: ");
for (int x : arr) [Link](x + " ");
[Link]();
[Link]();
}
}
SAMPLE OUTPUT
Enter size of array: 4
Enter 4 elements: 5 10 15 20
Array elements: 5 10 15 20
04 2-D array traversal using .length
Class: MatrixLengthDemo — single utility class.
public class MatrixLengthDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link]("Rows = " + [Link]);
[Link]("Columns = " + matrix[0].length);
[Link]("Matrix:");
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link]("%4d", matrix[i][j]);
}
[Link]();
}
}
}
SAMPLE OUTPUT
Rows = 3
Columns = 3
Matrix:
1 2 3
4 5 6
7 8 9
05 Decimal to Binary conversion
Class: DecimalToBinaryConverter — single utility class.
Java Practicals – Tanushree Paul Page 4
public class DecimalToBinaryConverter {
public static void main(String[] args) {
int decimal = 45;
String binary = "";
int n = decimal;
while (n > 0) {
binary = (n % 2) + binary;
n /= 2;
}
[Link]("Decimal : " + decimal);
[Link]("Binary : " + binary);
[Link]("Built-in: " + [Link](decimal));
}
}
SAMPLE OUTPUT
Decimal : 45
Binary : 101101
Built-in: 101101
06 Prime number check (keyboard input)
Class: PrimeChecker — single utility class.
import [Link];
public class PrimeChecker {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= [Link](n); i++)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
if (isPrime(num))
[Link](num + " is a Prime number.");
else
[Link](num + " is NOT a Prime number.");
[Link]();
}
}
SAMPLE OUTPUT
Enter a number: 17
17 is a Prime number.
07 Interactive N-integer sum + String/StringBuffer methods
Two independent programs — InteractiveSum (Part A) and StringBufferDemo (Part B).
Java Practicals – Tanushree Paul Page 5
// Part A: [Link]
import [Link];
public class InteractiveSum {
public static void main(String[] args) {
int n = [Link](args[0]);
Scanner sc = new Scanner([Link]);
int sum = 0;
[Link]("Enter " + n + " integers:");
for (int i = 0; i < n; i++) sum += [Link]();
[Link]("Sum = " + sum);
[Link]();
}
}
// Part B: [Link]
public class StringBufferDemo {
public static void main(String[] args) {
// --- String ---
String s1 = "Hello";
String s2 = " World";
[Link]("concat() : " + [Link](s2));
[Link]("equals() : " + [Link]("Hello"));
[Link]("charAt(1) : " + [Link](1));
// --- StringBuffer ---
StringBuffer sb = new StringBuffer("Java");
[Link]("Original : " + sb);
[Link](" Programming");
[Link]("append() : " + sb);
[Link](4, " OOP");
[Link]("insert() : " + sb);
[Link](0, 'j');
[Link]("setCharAt : " + sb);
[Link](12);
[Link]("setLength : " + sb);
}
}
SAMPLE OUTPUT
// Part A (run: java InteractiveSum 3)
Enter 3 integers:
10 20 30
Sum = 60
// Part B
concat() : Hello World
equals() : true
charAt(1) : e
Original : Java
append() : Java Programming
insert() : Java OOP Programming
setCharAt : java OOP Programming
setLength : java OOP Pr
08 Distance class – objects and the 'this' keyword
Split: Distance (logic) + DistanceDemo (driver with main).
Java Practicals – Tanushree Paul Page 6
class Distance {
int feet, inches;
void setDistance(int feet, int inches) {
[Link] = feet; // 'this' distinguishes field from parameter
[Link] = inches;
}
Distance addDistance(Distance d) {
Distance result = new Distance();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link] + [Link] / 12;
[Link] %= 12;
return result;
}
void display() {
[Link](feet + " feet " + inches + " inches");
}
}
public class DistanceDemo {
public static void main(String[] args) {
Distance d1 = new Distance();
Distance d2 = new Distance();
[Link](5, 9);
[Link](3, 7);
[Link]("d1 = "); [Link]();
[Link]("d2 = "); [Link]();
Distance d3 = [Link](d2);
[Link]("d1 + d2 = "); [Link]();
}
}
SAMPLE OUTPUT
d1 = 5 feet 9 inches
d2 = 3 feet 7 inches
d1 + d2 = 9 feet 4 inches
09 Distance class – constructors, reference vs. clone
Split: Distance (logic) + DistanceCloneDemo (driver with main).
Java Practicals – Tanushree Paul Page 7
class Distance implements Cloneable {
int feet, inches;
// Default constructor
Distance() { feet = 0; inches = 0; }
// Parameterized constructor
Distance(int f, int i) { feet = f; inches = i; }
// Copy constructor (clone)
Distance(Distance d) {
[Link] = [Link];
[Link] = [Link];
}
void display(String label) {
[Link](label + ": " + feet + "ft " + inches + "in");
}
}
public class DistanceCloneDemo {
public static void main(String[] args) {
Distance obj1 = new Distance(7, 5);
[Link]("obj1");
// obj2 is a reference to the SAME object as obj1
Distance obj2 = obj1;
[Link]("obj2 (ref of obj1)");
// obj3 is a CLONE (independent copy) of obj1
Distance obj3 = new Distance(obj1);
[Link]("obj3 (clone of obj1)");
// Modifying obj2 also changes obj1 (same object)
[Link] = 10;
[Link]();
[Link]("After [Link] = 10:");
[Link]("obj1"); [Link]("obj2"); [Link]("obj3");
}
}
SAMPLE OUTPUT
obj1: 7ft 5in
obj2 (ref of obj1): 7ft 5in
obj3 (clone of obj1): 7ft 5in
After [Link] = 10:
obj1: 10ft 5in
obj2: 10ft 5in
obj3: 7ft 5in
10 Method overloading with automatic type promotion
Class: TypePromotionDemo — overloaded static methods, single class (no object state to separate out).
Java Practicals – Tanushree Paul Page 8
public class TypePromotionDemo {
static void show(long x) {
[Link]("show(long) called with value = " + x);
}
static void show(double x) {
[Link]("show(double) called with value = " + x);
}
static void show(float x) {
[Link]("show(float) called with value = " + x);
}
public static void main(String[] args) {
int i = 10;
byte b = 20;
short s = 30;
long l = 40L;
float f = 5.5f;
show(i); // int -> long
show(b); // byte -> long
show(s); // short -> long
show(l); // exact match long
show(f); // exact match float
}
}
SAMPLE OUTPUT
show(long) called with value = 10
show(long) called with value = 20
show(long) called with value = 30
show(long) called with value = 40
show(float) called with value = 5.5
11 Access specifiers, pass-by-value vs. reference, final
Split: AccessDemo (logic) + AccessSpecifierDemo (driver with main).
Java Practicals – Tanushree Paul Page 9
class AccessDemo {
public int pubVal = 100; // accessible everywhere
private int privVal = 200; // accessible only inside class
final int CONST = 999; // cannot be changed
public int getPrivVal() { return privVal; }
// Primitive - passed by value
void incrementVal(int x) { x += 10; }
// Object - passed by reference
void incrementObj(AccessDemo obj) { [Link] += 10; }
}
public class AccessSpecifierDemo {
public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
[Link]("public value : " + [Link]);
// [Link] is NOT accessible here -> compile error if uncommented
[Link]("private (via getter) : " + [Link]());
[Link]("final constant : " + [Link]);
// Pass by value
int num = 50;
[Link](num);
[Link]();
[Link]("After incrementVal (pass by value): " + num); // unchanged
// Pass by reference
[Link](obj);
[Link]("After incrementObj (pass by ref) : " + [Link]); // changed
}
}
SAMPLE OUTPUT
public value : 100
private (via getter) : 200
final constant : 999
After incrementVal (pass by value): 50
After incrementObj (pass by ref) : 110
12 Static methods and varargs
Class: VarargsDemo — single utility class.
Java Practicals – Tanushree Paul Page 10
public class VarargsDemo {
// Static method - called without an object
static int add(int... nums) { // varargs
int sum = 0;
for (int n : nums) sum += n;
return sum;
}
static double average(double... vals) {
double sum = 0;
for (double v : vals) sum += v;
return [Link] == 0 ? 0 : sum / [Link];
}
static void printAll(String... words) {
[Link]("Words: ");
for (String w : words) [Link](w + " ");
[Link]();
}
public static void main(String[] args) {
[Link]("add(1,2,3) = " + add(1, 2, 3));
[Link]("add(10,20,30,40,50) = " + add(10, 20, 30, 40, 50));
[Link]("average(4.0,6.0,8.0) = %.2f%n", average(4.0, 6.0, 8.0));
printAll("Java", "is", "fun");
}
}
SAMPLE OUTPUT
add(1,2,3) = 6
add(10,20,30,40,50) = 150
average(4.0,6.0,8.0) = 6.00
Words: Java is fun
13 Autoboxing and unboxing
Class: BoxingUnboxingDemo — single utility class.
Java Practicals – Tanushree Paul Page 11
public class BoxingUnboxingDemo {
public static void main(String[] args) {
// BOXING: primitive -> wrapper object
int pInt = 42;
Integer boxed = pInt; // auto-boxing
double pDouble = 3.14;
Double boxedD = pDouble; // auto-boxing
[Link]("Primitive int : " + pInt);
[Link]("Boxed Integer : " + boxed);
[Link]("Primitive double : " + pDouble);
[Link]("Boxed Double : " + boxedD);
// UNBOXING: wrapper object -> primitive
Integer obj = 100;
int unboxed = obj; // auto-unboxing
[Link]();
[Link]("Boxed Integer : " + obj);
[Link]("Unboxed int : " + unboxed);
// Arithmetic with wrapper objects (unboxing happens automatically)
Integer a = 15, b = 25;
int sum = a + b; // unboxed, then added
[Link]();
[Link](a + " + " + b + " = " + sum);
// Comparing boxed integers
Integer x = 127, y = 127;
[Link]();
[Link]("x == y (cached): " + (x == y)); // true (cache)
Integer p = 200, q = 200;
[Link]("p == q (>127) : " + (p == q)); // false (new objs)
[Link]("[Link](q) : " + [Link](q)); // true
}
}
SAMPLE OUTPUT
Primitive int : 42
Boxed Integer : 42
Primitive double : 3.14
Boxed Double : 3.14
Boxed Integer : 100
Unboxed int : 100
15 + 25 = 40
x == y (cached): true
p == q (>127) : false
[Link](q) : true
14 Multi-file program – input in one file, output in another
Split across files: MessageDisplay (logic) + MessageApp (driver with main).
Java Practicals – Tanushree Paul Page 12
// ----- File 1: [Link] -----
public class MessageDisplay {
public void display(String message) {
[Link]("Message: " + message);
}
}
// ----- File 2: [Link] (main file) -----
import [Link];
public class MessageApp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a message: ");
String msg = [Link]();
[Link]();
MessageDisplay md = new MessageDisplay();
[Link](msg);
}
}
// Compilation & Run:
// javac [Link] [Link]
// java MessageApp
SAMPLE OUTPUT
Enter a message: Hello Java World!
Message: Hello Java World!
15 Multilevel package with a Fibonacci generator
Split across files: Fibonacci (logic) + FibonacciApp (driver with main).
Java Practicals – Tanushree Paul Page 13
// Directory structure:
// mypackage/math/[Link]
// mypackage/math/[Link]
// ----- File 1: mypackage/math/[Link] -----
package [Link];
public class Fibonacci {
public void generate(int n) {
[Link]("Fibonacci series: ");
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
[Link](a + " ");
int temp = a + b;
a = b;
b = temp;
}
[Link]();
}
}
// ----- File 2: mypackage/math/[Link] -----
package [Link];
public class FibonacciApp {
public static void main(String[] args) {
Fibonacci fib = new Fibonacci();
[Link](10);
}
}
// Compile & Run from project root:
// javac mypackage/math/[Link] mypackage/math/[Link]
// java [Link]
SAMPLE OUTPUT
Fibonacci series: 0 1 1 2 3 5 8 13 21 34
16 Protection levels across classes/packages
Split across packages: BaseClass, SamePackageClass, DiffPackageSubclass + ProtectionDemo (driver).
Java Practicals – Tanushree Paul Page 14
// ----- package1/[Link] -----
package package1;
public class BaseClass {
public int publicVar = 1; // everywhere
protected int protectedVar = 2; // same pkg + subclasses
int defaultVar = 3; // same package only
private int privateVar = 4; // this class only
public void showAll() {
[Link]("public=" + publicVar);
[Link]("protected=" + protectedVar);
[Link]("default=" + defaultVar);
[Link]("private=" + privateVar);
}
}
// ----- package1/[Link] -----
package package1;
public class SamePackageClass extends BaseClass {
public void show() {
[Link]("public=" + publicVar); // OK
[Link]("protected=" + protectedVar); // OK
[Link]("default=" + defaultVar); // OK
// privateVar NOT accessible here
}
}
// ----- package2/[Link] -----
package package2;
import [Link];
public class DiffPackageSubclass extends BaseClass {
public void show() {
[Link]("public=" + publicVar); // OK
[Link]("protected=" + protectedVar); // OK (inherited)
// defaultVar NOT accessible (different package)
// privateVar NOT accessible
}
}
// ----- package2/[Link] -----
package package2;
import [Link];
import [Link];
public class ProtectionDemo {
public static void main(String[] args) {
BaseClass b = new BaseClass();
[Link]("From outside -> public: " + [Link]);
// Only publicVar accessible from here
SamePackageClass sc = new SamePackageClass();
[Link]();
DiffPackageSubclass ds = new DiffPackageSubclass();
[Link]();
}
}
SAMPLE OUTPUT
Java Practicals – Tanushree Paul Page 15
From outside -> public: 1
public=1 protected=2 default=3 (SamePackageClass)
public=1 protected=2 (DiffPackageSubclass)
17 ArithmeticException – divide by zero
Class: DivideByZeroDemo — single utility class.
import [Link];
public class DivideByZeroDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter numerator (a): ");
int a = [Link]();
[Link]("Enter denominator (b): ");
int b = [Link]();
try {
int result = a / b;
[Link](a + " / " + b + " = " + result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
[Link]("Cannot divide by zero!");
} finally {
[Link]("Program execution complete.");
[Link]();
}
}
}
SAMPLE OUTPUT
Enter numerator (a): 10
Enter denominator (b): 0
Exception caught: / by zero
Cannot divide by zero!
Program execution complete.
18 Nested try blocks and catch ordering
Class: NestedTryDemo — single utility class.
Java Practicals – Tanushree Paul Page 16
public class NestedTryDemo {
public static void main(String[] args) {
int[] arr = {10, 20, 0, 5};
try { // outer try
[Link]("Outer try block start");
try { // inner try 1
int result = arr[1] / arr[2]; // division by zero
[Link]("Result = " + result);
} catch (ArithmeticException e) {
[Link]("Inner catch 1: " + [Link]());
}
try { // inner try 2
int val = arr[10]; // array index out of bounds
[Link]("val = " + val);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch 2: " + [Link]());
}
[Link]("Outer try block end");
} catch (Exception e) {
[Link]("Outer catch: " + [Link]());
} finally {
[Link]("Outer finally block executed.");
}
}
}
SAMPLE OUTPUT
Outer try block start
Inner catch 1: / by zero
Inner catch 2: Index 10 out of bounds for length 4
Outer try block end
Outer finally block executed.
19 User-defined custom exception
Split: InsufficientFundsException + BankAccount (logic) + CustomExceptionDemo (driver).
Java Practicals – Tanushree Paul Page 17
// Custom exception (subclass of Exception)
class InsufficientFundsException extends Exception {
private double amount;
InsufficientFundsException(double amount) {
super("Insufficient funds! Short by: Rs. " + amount);
[Link] = amount;
}
double getAmount() { return amount; }
}
class BankAccount {
private double balance;
BankAccount(double balance) { [Link] = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
[Link]("Withdrawn: Rs. " + amount + " | Balance: Rs. " + balance);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000.0);
try {
[Link](3000);
[Link](3000); // this will throw
} catch (InsufficientFundsException e) {
[Link]("Caught: " + [Link]());
[Link]("Shortage: Rs. %.2f%n", [Link]());
}
}
}
SAMPLE OUTPUT
Withdrawn: Rs. 3000.0 | Balance: Rs. 2000.0
Caught: Insufficient funds! Short by: Rs. 1000.0
Shortage: Rs. 1000.00
20 Thread priority demonstration
Split: PriorityThread (logic) + ThreadPriorityDemo (driver with main).
Java Practicals – Tanushree Paul Page 18
class PriorityThread extends Thread {
PriorityThread(String name, int priority) {
super(name);
setPriority(priority);
}
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](getName() +
" (Priority " + getPriority() + ") -> step " + i);
[Link](); // give other threads a chance
}
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) throws InterruptedException {
PriorityThread low = new PriorityThread("LOW", Thread.MIN_PRIORITY);
PriorityThread normal = new PriorityThread("NORMAL", Thread.NORM_PRIORITY);
PriorityThread high = new PriorityThread("HIGH", Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
[Link](); [Link](); [Link]();
[Link]("All threads finished.");
}
}
SAMPLE OUTPUT
HIGH (Priority 10) -> step 1
HIGH (Priority 10) -> step 2
HIGH (Priority 10) -> step 3
NORMAL (Priority 5) -> step 1
NORMAL (Priority 5) -> step 2
NORMAL (Priority 5) -> step 3
LOW (Priority 1) -> step 1
LOW (Priority 1) -> step 2
LOW (Priority 1) -> step 3
All threads finished.
(Note: Actual order may vary by JVM/OS scheduler)
21 Producer-Consumer with synchronization
Split: SharedBuffer, Producer, Consumer (logic) + ProducerConsumerDemo (driver).
Java Practicals – Tanushree Paul Page 19
class SharedBuffer {
private int data;
private boolean hasData = false;
synchronized void produce(int value) throws InterruptedException {
while (hasData) wait(); // wait if buffer is full
data = value;
hasData = true;
[Link]("Produced: " + data);
notifyAll(); // notify consumer
}
synchronized int consume() throws InterruptedException {
while (!hasData) wait(); // wait if buffer is empty
hasData = false;
[Link]("Consumed: " + data);
notifyAll(); // notify producer
return data;
}
}
class Producer extends Thread {
SharedBuffer buffer;
Producer(SharedBuffer b) { buffer = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
try { [Link](i); [Link](100); }
catch (InterruptedException e) { [Link](); }
}
}
}
class Consumer extends Thread {
SharedBuffer buffer;
Consumer(SharedBuffer b) { buffer = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
try { [Link](); [Link](150); }
catch (InterruptedException e) { [Link](); }
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
SharedBuffer buffer = new SharedBuffer();
Producer p = new Producer(buffer);
Consumer c = new Consumer(buffer);
[Link](); [Link]();
[Link](); [Link]();
[Link]("Producer-Consumer complete.");
}
}
SAMPLE OUTPUT
Java Practicals – Tanushree Paul Page 20
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Producer-Consumer complete.
Java Practicals – Tanushree Paul Page 21