Java Programming
Lab Practicals – All 21 Programs
Prepared by: Tanushree Paul
Subject: Java OOP | [Link]. CS – 4th Semester
Q# Topic
Q1 Sum of integers from command line arguments
Q2 Factorial of a given number
Q3 Single dimensional array defined dynamically
Q4 Use of .length with a two-dimensional array
Q5 Decimal to Binary conversion
Q6 Check if a number is prime (keyboard input)
Q7 Sum of N integers interactively (N from command line) + String/StringBuffer methods
Q8 Distance class with feet and inches, objects and 'this' pointer
Q9 Distance class with constructors, reference variable, and clone object
Q10 Function overloading with automatic type conversion
Q11 public/private access, pass by value vs reference, final keyword
Q12 Static functions and variable-length arguments (varargs)
Q13 Boxing and Unboxing
Q14 Multi-file program: input in one file, display in another
Q15 Multilevel package with Fibonacci class in separate file
Q16 Protection levels in classes/subclasses in same and different packages
Q17 Divide by Zero – ArithmeticException
Q18 Nested try statements and catch handler sequence
Q19 User-defined custom exception class
Q20 Thread priorities demonstration
Q21 Multithreaded communication – Producer-Consumer with synchronization
Q1. Sum of integers from command line arguments
public class Q1SumCmdArgs {
public static void main(String[] args) {
int sum = 0;
for (String arg : args) {
sum += [Link](arg);
}
[Link]("Sum = " + sum);
}
}
Sample Output:
$ javac [Link]
$ java Q1SumCmdArgs 10 20 30 40
Sum = 100
Q2. Factorial of a given number
public class Q2Factorial {
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
Q3. Single dimensional array defined dynamically
import [Link];
public class Q3DynamicArray {
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
Q4. Use of .length with a two-dimensional array
public class Q4TwoDArray {
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
Q5. Decimal to Binary conversion
public class Q5DecToBin {
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);
// Using built-in method
[Link]("Built-in: " + [Link](decimal));
}
}
Sample Output:
Decimal: 45
Binary : 101101
Built-in: 101101
Q6. Check if a number is prime (keyboard input)
import [Link];
public class Q6PrimeCheck {
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.
Q7. Sum of N integers interactively (N from command line) + String/StringBuffer
methods
// Part A: Sum of N integers interactively
import [Link];
public class Q7SumInteractive {
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: String and StringBuffer methods
public class Q7StringMethods {
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 Q7SumInteractive 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
Q8. Distance class with feet and inches, objects and 'this' pointer
public class Q8Distance {
int feet, inches;
void setDistance(int feet, int inches) {
[Link] = feet; // 'this' distinguishes field from parameter
[Link] = inches;
}
Q8Distance addDistance(Q8Distance d) {
Q8Distance result = new Q8Distance();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link] + [Link] / 12;
[Link] %= 12;
return result;
}
void display() {
[Link](feet + " feet " + inches + " inches");
}
public static void main(String[] args) {
Q8Distance d1 = new Q8Distance();
Q8Distance d2 = new Q8Distance();
[Link](5, 9);
[Link](3, 7);
[Link]("d1 = "); [Link]();
[Link]("d2 = "); [Link]();
Q8Distance 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
Q9. Distance class with constructors, reference variable, and clone object
public class Q9DistanceConstructor implements Cloneable {
int feet, inches;
// Default constructor
Q9DistanceConstructor() { feet = 0; inches = 0; }
// Parameterized constructor
Q9DistanceConstructor(int f, int i) { feet = f; inches = i; }
// Copy constructor (clone)
Q9DistanceConstructor(Q9DistanceConstructor d) {
[Link] = [Link];
[Link] = [Link];
}
void display(String label) {
[Link](label + ": " + feet + "ft " + inches + "in");
}
public static void main(String[] args) {
Q9DistanceConstructor obj1 = new Q9DistanceConstructor(7, 5);
[Link]("obj1");
// obj2 is a reference to the SAME object as obj1
Q9DistanceConstructor obj2 = obj1;
[Link]("obj2 (ref of obj1)");
// obj3 is a CLONE (independent copy) of obj1
Q9DistanceConstructor obj3 = new Q9DistanceConstructor(obj1);
[Link]("obj3 (clone of obj1)");
// Modifying obj2 also changes obj1 (same object)
[Link] = 10;
[Link]("\nAfter [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
Q10. Function overloading with automatic type conversion
public class Q10AutoTypeConversion {
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;
// No exact match for int -> promoted to long
show(i); // int -> long
// No exact match for byte -> promoted to long
show(b); // byte -> long
// No exact match for short -> promoted to 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
Q11. public/private access, pass by value vs reference, final keyword
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 Q11AccessSpecifiers {
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]("\nAfter 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
Q12. Static functions and variable-length arguments (varargs)
public class Q12StaticVarargs {
// 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
Q13. Boxing and Unboxing
public class Q13BoxingUnboxing {
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 = new Integer(100);
int unboxed = obj; // auto-unboxing
[Link]("\nBoxed 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]("\n" + a + " + " + b + " = " + sum);
// Comparing boxed integers
Integer x = 127, y = 127;
[Link]("\nx == 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
Q14. Multi-file program: input in one file, display in another
// ----- File 1: [Link] -----
public class MessageDisplay {
public void display(String message) {
[Link]("Message: " + message);
}
}
// ----- File 2: [Link] (main file) -----
import [Link];
public class Q14Main {
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 Q14Main
Sample Output:
Enter a message: Hello Java World!
Message: Hello Java World!
Q15. Multilevel package with Fibonacci class in separate file
// 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 Q15Main {
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].Q15Main
Sample Output:
Fibonacci series: 0 1 1 2 3 5 8 13 21 34
Q16. Protection levels in classes/subclasses in same and different packages
// ----- 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 Q16Main {
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:
From outside -> public: 1
public=1 protected=2 default=3 (SamePackageClass)
public=1 protected=2 (DiffPackageSubclass)
Q17. Divide by Zero – ArithmeticException
import [Link];
public class Q17DivideByZero {
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.
Q18. Nested try statements and catch handler sequence
public class Q18NestedTry {
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.
Q19. User-defined custom exception class
// 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 Q19CustomException {
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
Q20. Thread priorities demonstration
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 Q20ThreadPriority {
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)
Q21. Multithreaded communication – Producer-Consumer with synchronization
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 Q21ProducerConsumer {
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:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Producer-Consumer complete.