1 of 43
Object Oriented Programming Lab using
Java
2 of 43
INDEX
SN NO Exercise/Practical (Outcomes in Psychomotor Domain)
1 Install JDK, write a simple “Hello World” or similar java program,
compilation, debugging, executing using java compiler and interpreter.
2 Write a program in Java to generate first n prime numbers.
3 Write a program in Java to find maximum of three numbers using
conditional operator
4 Write a program in Java to find second maximum of n numbers
without using arrays
5 Write a program in Java to reverse the digits of a number using while
loop
6 Write a program in Java to convert number into words & print it
7 Write programs in Java to use Wrapper class of each primitive data
types
8 Write a program in Java to multiply two matrix
9 Write a static block which will be executed before main( ) method in a
class.
10 Write a program in Java to demonstrate use of this keyword. Check
whether this can access the private members of the class or not.
11 Write a program in Java to develop overloaded constructor. Also develop
the copy constructor to create a new object with the state of
the existing object.
12 Write a program in Java to demonstrate the use of private constructor and
also write a method which will count the number of instances
created using default constructor only.
13 Write a program in Java to demonstrate the use of 'final' keyword in
the field declaration. How it is accessed using the objects.
14 Develop minimum 4 program based on variation in methods i.e.
passing by value, passing by reference, returning values and returning
objects from methods.
15 Write a program in Java to demonstrate single inheritance, multilevel
inheritance and hierarchical inheritance.
16 Create a class to find out whether the given year is leap year or not.
(Use inheritance for this program)
3 of 43
SN NO Exercise/Practical (Outcomes in Psychomotor Domain)
17 Write an application that illustrates how to access a hidden variable. Class A
declares a static variable x. The class B extends A and declares an instance
variable x. display( ) method in B displays both of these
variables.
18 Write a program in Java in which a subclass constructor invokes the
constructor of the super class and instantiate the values.
19 Write a program that illustrates interface inheritance. Interface P12
inherits from both P1 and P2. Each interface declares one constant and
one method. The class Q implements P12. Instantiate Q and invoke
each of its methods. Each method displays one of the constants.
20 Write an application that illustrates method overriding in the same package
and different packages. Also demonstrate accessibility rules in
inside and outside packages
21 Describe abstract class called Shape which has three subclasses say
Triangle, Rectangle, Circle. Define one method area()in the abstract class
and override this area() in these three subclasses to calculate for specific
object i.e. area() of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle
22 Write a program in Java to demonstrate implementation of multiple
inheritance using interfaces.
23 Write a program in Java to demonstrate use of final class.
24 Write a program in Java to develop user defined exception for 'Divide
by Zero' error.
25 Write a program in Java to demonstrate multiple try block and multiple
catch exception
26 Write an small application in Java to develop Banking Application in which
user deposits the amount Rs 1000.00 and then start withdrawing of Rs
400.00, Rs 300.00 and it throws exception "Not Sufficient Fund"
when user withdraws Rs. 500 thereafter.
27 Write a program that executes two threads. One thread displays “Thread1”
every 2,000 milliseconds, and the other displays “Thread2” every 4,000
milliseconds. Create the threads by extending the Thread class
28 Write a program that executes two threads. One thread will print the
even numbers and the another thread will print odd numbers from 1 to 50.
29 Write a program in Java to demonstrate use of synchronization of
threads when multiple threads are trying to update common variable.
30 Write a program in Java to create, write, modify, read operations on a text file
4 of 43
1. Install JDK, write a simple “Hello World” or similar java program, compilation, debugging,
executing using java compiler and interpreter ?
Step 1: Install the Java Development Kit (JDK)
The JDK is essential for compiling and running Java applications.
1. Download JDK:
◦ Go to the of cial Oracle JDK download page: https://www.oracle.com/
java/technologies/downloads/
◦ Choose the appropriate JDK version for your operating system (Windows, macOS,
Linux) and architecture (x64).
◦ Follow the download and installation instructions provided on the Oracle website.
2. Set Environment Variables (Crucial Step): After installation, you need to set up
environment variables so your operating system knows where to nd the Java compiler
(javac) and runtime (java).
◦ Windows:
1. Search for "Environment Variables" in the Start Menu and select "Edit the
system environment variables".
2. Click on "Environment Variables..." button.
3. Under "System variables", click "New..." to create a new variable:
▪ Variable name: JAVA_HOME
▪ Variable value: The path to your JDK installation directory (e.g., C:
\Program Files\Java\jdk-17 or C:\Program
Files\Java\jdk-21).
4. Find the Path variable under "System variables", select it, and click
"Edit...".
5. Click "New" and add %JAVA_HOME%\bin to the list.
6. Click "OK" on all windows to save changes.
7. Verify installation: Open a new Command Prompt and type java
-version and javac -version. You should see the installed JDK
versions.
fi
fi
5 of 43
◦ macOS/Linux:
1. Open your terminal.
2. Find your JDK installation path. It's usually something like /Library/
Java/JavaVirtualMachines/jdk-17.jdk/Contents/
Home on macOS or /usr/lib/jvm/java-17-openjdk/ on
Linux.
3. Edit your shell con guration le (e.g., ~/.bashrc, ~/.zshrc, or
~/.profile). You can use a text editor like nano or vi: nano
~/.bashrc
4. Add the following lines to the end of the le, replacing the path with your
actual JDK path:
export JAVA_HOME="/path/to/your/jdk"
5. export PATH=$PATH:$JAVA_HOME/bin
6. Save the le and exit the editor.
7. Apply the changes by sourcing the le: source ~/.bashrc (or
source ~/.zshrc, etc.)
8. Verify installation: Open a new Terminal and type java -version and
javac -version. You should see the installed JDK versions.
Step 2: Write a Simple Java Program
Let's create a classic "Hello World" program.
1. Open a plain text editor (like Notepad on Windows, TextEdit on macOS, Gedit/VS Code/
Sublime Text on Linux).
2. Save the le as HelloWorld.java. The le name must exactly match the class
name, including case.
3. Copy and paste the following code into the le:
Step 3: Compile the Java Program
The Java compiler (javac) translates your human-readable Java source code (.java le) into
bytecode (.class le), which is platform-independent.
1. Open your Command Prompt (Windows) or Terminal (macOS/Linux).
2. Navigate to the directory where you saved HelloWorld.java using the cd command.
◦ Example: If you saved it in C:\Users\YourUser\JavaProjects, type
cd C:\Users\YourUser\JavaProjects
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
6 of 43
◦ Example: If you saved it in /home/youruser/java_programs, type
cd /home/youruser/java_programs
3. Compile the program using javac:
If there are no compilation errors, this command will create a le named HelloWorld.class
in the same directory. If you see errors, double-check your code for typos (e.g., missing semicolons,
incorrect capitalization).
Step 4: Execute the Java Program
The Java interpreter (java) runs the compiled bytecode.
1. While still in the same directory in your Command Prompt/Terminal, execute the program
using java:
Step 5: Basic Debugging Concepts
Debugging is the process of nding and xing errors (bugs) in your code. For simple programs, the
most common debugging technique is using print statements.
• Using System.out.println() for Debugging: You can insert
System.out.println() statements at various points in your code to inspect the
value of variables or to con rm that certain parts of your code are being executed.
For example, if you had a variable count:
fi
fi
fi
fi
7 of 43
2. Write a program in Java to generate rst n prime numbers ?
import java.util.Scanner;
public class FirstNPrimes {
// Method to check if a number is prime
public static boolean isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int count = 0;
int num = 2;
System.out.println("First " + n + " prime numbers are:");
while (count < n) {
if (isPrime(num)) {
System.out.print(num + " ");
count++;
}
num++;
}
sc.close();
}
}
Sample Output
Enter the value of n: 10
First 10 prime numbers are:
2 3 5 7 11 13 17 19 23 29
fi
8 of 43
3. Write a program in Java to nd maximum of three numbers using conditional operator ?
Here is a simple Java program to nd the maximum of three numbers using the conditional
(ternary) operator:
public class MaxOfThree {
public static void main(String[] args) {
int a = 25;
int b = 50;
int c = 40;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
System.out.println("The maximum of " + a + ", " + b + ", and " + c + " is: " + max);
}
}
}
}
Sample output
The maximum of 25, 50, and 40 is: 50
fi
fi
9 of 43
4. Write a program in Java to nd second maximum of n numbers without using arrays?
import java.util.Scanner;
public class SecondMaximum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
int n = scanner.nextInt();
if (n < 2) {
System.out.println("Need at least two numbers to nd second maximum.");
return;
}
System.out.print("Enter number 1: ");
int max = scanner.nextInt();
System.out.print("Enter number 2: ");
int num = scanner.nextInt();
int secondMax;
if (num > max) {
secondMax = max;
max = num;
} else {
secondMax = num;
}
for (int i = 3; i <= n; i++) {
System.out.print("Enter number " + i + ": ");
num = scanner.nextInt();
if (num > max) {
secondMax = max;
max = num;
} else if (num > secondMax && num != max) {
secondMax = num;
}
}
System.out.println("Second maximum number is: " + secondMax);
}
}
Sample Output
Enter how many numbers: 5
Enter number 1: 40
Enter number 2: 90
Enter number 3: 60
Enter number 4: 30
Enter number 5: 80
Second maximum number is: 80
fi
fi
10 of 43
5. Write a program in Java to reverse the digits of a number using while loop?
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reverse = 0;
int original = number;
while (number != 0) {
int digit = number % 10; // Extract last digit
reverse = reverse * 10 + digit; // Append digit to reverse
number /= 10; // Remove last digit
}
System.out.println("Reversed number of " + original + " is: " + reverse);
}
}
Sample Output
Enter a number: 12345
Reversed number of 12345 is: 54321
11 of 43
6. Write a program in Java to convert number into words & print it ?
import java.util.Scanner;
public class NumberToWords {
// Arrays to hold words for digits and tens
static String[] units = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
static String[] tens = {
"", "", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"
};
// Convert number to words
public static String convert(int number) {
if (number == 0) return "Zero";
if (number < 0) return "Minus " + convert(-number);
String words = "";
if ((number / 1000) > 0) {
words += units[number / 1000] + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0) {
words += units[number / 100] + " Hundred ";
number %= 100;
}
if (number > 0) {
if (number < 20) {
words += units[number];
} else {
words += tens[number / 10];
if ((number % 10) > 0) {
words += "-" + units[number % 10];
}
}
}
Sample Output
Enter a number (0 - 9999): 1947
In words: One Thousand Nine Hundred Forty-Seven
12 of 43
7. Write programs in Java to use Wrapper class of each primitive data types ?
public class WrapperClassDemo {
public static void main(String[] args) {
// Byte wrapper
byte b = 10;
Byte byteObj = Byte.valueOf(b);
System.out.println("Byte object: " + byteObj);
// Short wrapper
short s = 1000;
Short shortObj = Short.valueOf(s);
System.out.println("Short object: " + shortObj);
// Integer wrapper
int i = 12345;
Integer intObj = Integer.valueOf(i);
System.out.println("Integer object: " + intObj);
// Long wrapper
long l = 123456789L;
Long longObj = Long.valueOf(l);
System.out.println("Long object: " + longObj);
// Float wrapper
oat f = 3.14f;
Float oatObj = Float.valueOf(f);
System.out.println("Float object: " + oatObj);
// Double wrapper
double d = 99.99;
Double doubleObj = Double.valueOf(d);
System.out.println("Double object: " + doubleObj);
// Character wrapper
char c = 'A';
Character charObj = Character.valueOf(c);
System.out.println("Character object: " + charObj);
// Boolean wrapper
boolean bool = true;
Boolean boolObj = Boolean.valueOf(bool);
System.out.println("Boolean object: " + boolObj);
}
}
Sample Output
Byte object: 10
Short object: 1000
Integer object: 12345
Long object: 123456789
Float object: 3.14
Double object: 99.99
Character object: A
fl
fl
fl
13 of 43
8. Write a program in Java to multiply two matrix ?
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input dimensions
System.out.print("Enter number of rows of rst matrix: ");
int r1 = scanner.nextInt();
System.out.print("Enter number of columns of rst matrix (and rows of second matrix): ");
int c1 = scanner.nextInt();
System.out.print("Enter number of columns of second matrix: ");
int c2 = scanner.nextInt();
int[][] mat1 = new int[r1][c1];
int[][] mat2 = new int[c1][c2];
int[][] result = new int[r1][c2];
// Input rst matrix
System.out.println("Enter elements of rst matrix:");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
mat1[i][j] = scanner.nextInt();
}
}
// Input second matrix
System.out.println("Enter elements of second matrix:");
for (int i = 0; i < c1; i++) {
for (int j = 0; j < c2; j++) {
mat2[i][j] = scanner.nextInt();
}
}
// Multiply matrices
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
Sample Output
Enter number of rows of rst matrix: 2
Enter number of columns of rst matrix (and rows of second matrix): 2
Enter number of columns of second matrix: 2
Enter elements of rst matrix:
12
34
Enter elements of second matrix:
56
78
Product of the two matrices:
fi
fi
fi
fi
fi
fi
fi
14 of 43
9. Write a static block which will be executed before main( ) method in a class ?
public class StaticBlockDemo {
// Static block
static {
System.out.println("Static block is executed before main()");
}
public static void main(String[] args) {
System.out.println("main() method is executed.");
}
}
Sample Output
Static block is executed before main()
main() method is executed.
15 of 43
10. Write a program in Java to demonstrate use of this keyword. Check whether this can access the
private members of the class or not ?
public class ThisKeywordDemo {
// Private members
private int id;
private String name;
// Constructor using 'this' to refer to private members
public ThisKeywordDemo(int id, String name) {
this.id = id; // 'this' refers to current object's id
this.name = name; // 'this' refers to current object's name
}
// Method using 'this' to access private members
public void displayInfo() {
System.out.println("ID: " + this.id); // Accessing private member using 'this'
System.out.println("Name: " + this.name); // Accessing private member using 'this'
}
public static void main(String[] args) {
// Create object and call method
ThisKeywordDemo obj = new ThisKeywordDemo(101, "Aniket");
obj.displayInfo();
}
}
Sample Output
ID: 101
Name: Aniket
16 of 43
11. Write a program in Java to develop overloaded constructor. Also develop the copy constructor to
create a new object with the state of the existing object ?
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "Unknown";
}
// Overloaded constructor with parameters
Student(int id, String name) {
this.id = id;
this.name = name;
}
// Copy constructor
Student(Student s) {
this.id = s.id;
this.name = s.name;
}
// Method to display student details
void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
// Using default constructor
Student s1 = new Student();
System.out.print("Student 1: ");
s1.display();
// Using parameterized constructor
Student s2 = new Student(101, "Aniket");
System.out.print("Student 2: ");
s2.display();
// Using copy constructor
Student s3 = new Student(s2);
System.out.print("Student 3 (copied from Student 2): ");
s3.display();
}
}
17 of 43
Sample output
Student 1: ID: 0, Name: Unknown
Student 2: ID: 101, Name: Aniket
Student 3 (copied from Student 2): ID: 101, Name: Aniket
18 of 43
12 . Write a program in Java to demonstrate the use of private constructor and also write a method
which will count the number of instances created using default constructor only ?
class MyClass {
// Static variable to count instances
private static int count = 0;
// Public default constructor
public MyClass() {
count++;
System.out.println("Default constructor called.");
}
// Private constructor (cannot be accessed outside the class)
private MyClass(int x) {
System.out.println("Private constructor called with value: " + x);
}
// Static method to get the current count
public static int getInstanceCount() {
return count;
}
// Factory method to demonstrate private constructor usage within class
public static MyClass createUsingPrivateConstructor(int x) {
return new MyClass(x); // Allowed because it's within the same class
}
}
public class ConstructorTest {
public static void main(String[] args) {
// Create objects using default constructor
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// Create an object using private constructor (via a static method)
MyClass obj3 = MyClass.createUsingPrivateConstructor(100);
// Display number of instances created using default constructor
System.out.println("Number of instances created using default constructor: " +
MyClass.getInstanceCount());
}
}
Sample Output
Default constructor called.
Default constructor called.
Private constructor called with value: 100
Number of instances created using default constructor: 2
19 of 43
13. Write a program in Java to demonstrate the use of ' nal' keyword in the eld declaration. How
it is accessed using the objects ?
class Student {
// Final eld – must be initialized once and can't be changed
nal int rollNumber;
nal String collegeName = "ABC College"; // Directly initialized
// Constructor to initialize nal eld
Student(int rollNumber) {
this.rollNumber = rollNumber; // Final variable initialized in constructor
}
// Method to display nal elds
void display() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("College Name: " + collegeName);
}
}
public class FinalKeywordDemo {
public static void main(String[] args) {
// Create object of Student
Student s1 = new Student(101);
s1.display();
// Access nal eld using object
System.out.println("Accessed via object: " + s1.collegeName);
// s1.collegeName = "XYZ College"; // ❌ This will cause a compile-time error
}
}
Sample output
Roll Number: 101
College Name: ABC College
Accessed via object: ABC College
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
20 of 43
14. Develop minimum 4 program based on variation in methods i.e. passing by value, passing by
reference, returning values and returning objects from methods ?
1. Passing by Value (primitive types)
public class PassByValue {
static void changeValue(int x) {
x = x + 10;
System.out.println("Inside method: x = " + x);
}
public static void main(String[] args) {
int num = 5;
changeValue(num);
System.out.println("Outside method: num = " + num);
}
}
Sample Output
Inside method: x = 15
Outside method: num = 5
2. Passing by Reference (using objects)
class Number {
int value;
}
public class PassByReference {
static void modify(Number n) {
n.value = n.value + 20;
}
Sample output
Modi ed value: 30
fi
21 of 43
3. Returning Values from Method
public class ReturnValue {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int result = square(6);
System.out.println("Square: " + result);
}
Sample output
Square: 36
4. Returning Object from Method
class Person {
String name;
Person(String name) {
this.name = name;
}
// Method returns a new Person object
static Person getPerson() {
return new Person("Aniket");
}
void display() {
System.out.println("Name: " + name);
}
}
public class ReturnObject {
public static void main(String[] args) {
Person p = Person.getPerson(); // Get object from method
p.display();
}
}
Sample output
Name: Aniket
22 of 43
15. Write a program in Java to demonstrate single inheritance, multilevel inheritance and
hierarchical inheritance.
Here's a Java program that demonstrates all three types of inheritance:
// Base class
class Animal {
void eat() {
System.out.println("Animal eats food.");
}
}
// ----------- Single Inheritance ------------
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
// ----------- Multilevel Inheritance ------------
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps.");
}
}
// ----------- Hierarchical Inheritance ------------
class Cat extends Animal {
void meow() {
System.out.println("Cat meows.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
System.out.println("--- Single Inheritance ---");
Dog dog = new Dog();
dog.eat(); // From Animal
dog.bark(); // From Dog
System.out.println("\n--- Multilevel Inheritance ---");
Puppy puppy = new Puppy();
puppy.eat(); // From Animal
puppy.bark(); // From Dog
puppy.weep(); // From Puppy
System.out.println("\n--- Hierarchical Inheritance ---");
Cat cat = new Cat();
cat.eat(); // From Animal
cat.meow(); // From Cat
}
}
23 of 43
Sample output
--- Single Inheritance ---
Animal eats food.
Dog barks.
--- Multilevel Inheritance ---
Animal eats food.
Dog barks.
Puppy weeps.
--- Hierarchical Inheritance ---
Animal eats food.
Cat meows.
24 of 43
16. Create a class to nd out whether the given year is leap year or not. (Use inheritance for this
program)
// Base class
class Year {
int year;
Year(int year) {
this.year = year;
}
}
// Derived class using inheritance
class LeapYearChecker extends Year {
LeapYearChecker(int year) {
super(year); // Call parent constructor
}
void checkLeapYear() {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a Leap Year.");
} else {
System.out.println(year + " is NOT a Leap Year.");
}
}
}
// Main class
public class LeapYearDemo {
public static void main(String[] args) {
LeapYearChecker y1 = new LeapYearChecker(2024);
y1.checkLeapYear();
LeapYearChecker y2 = new LeapYearChecker(1900);
y2.checkLeapYear();
LeapYearChecker y3 = new LeapYearChecker(2000);
y3.checkLeapYear();
}
}
Sample output
2024 is a Leap Year.
1900 is NOT a Leap Year.
2000 is a Leap Year.
fi
25 of 43
17. Write an application that illustrates how to access a hidden variable. Class A declares a static
variable x. The class B extends A and declares an instance variable x. display( ) method in B
displays both of these variables.
// Superclass A
class A {
static int x = 10; // Static variable in superclass
}
// Subclass B
class B extends A {
int x = 20; // Instance variable hiding superclass variable
void display() {
System.out.println("Superclass static x (A.x): " + A.x);
System.out.println("Subclass instance x (this.x): " + this.x);
}
}
// Main class
public class HiddenVariableDemo {
public static void main(String[] args) {
B obj = new B();
obj.display();
}
}
Sample output
Superclass static x (A.x): 10
Subclass instance x (this.x): 20
26 of 43
18. Write a program in Java in which a subclass constructor invokes the constructor of the super
class and instantiate the values.
// Superclass
class Person {
String name;
int age;
// Superclass constructor
Person(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Person constructor called.");
}
}
// Subclass
class Student extends Person {
int rollNumber;
// Subclass constructor calling superclass constructor
Student(String name, int age, int rollNumber) {
super(name, age); // Call to superclass constructor
this.rollNumber = rollNumber;
System.out.println("Student constructor called.");
}
// Method to display student details
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Roll Number: " + rollNumber);
}
}
// Main class
public class ConstructorChainingDemo {
public static void main(String[] args) {
Student s = new Student("Aniket", 20, 101);
s.display();
}
}
Sample output
Person constructor called.
Student constructor called.
Name: Aniket
Age: 20
Roll Number: 101
27 of 43
19. Write a program that illustrates interface inheritance. Interface P12 inherits from both P1 and
P2. Each interface declares one constant and one method. The class Q implements P12. Instantiate
Q and invoke each of its methods. Each method displays one of the constants ?
// Interface P1
interface P1 {
int A = 10; // constant
void showA(); // method
}
// Interface P2
interface P2 {
int B = 20; // constant
void showB(); // method
}
// Interface P12 inherits P1 and P2
interface P12 extends P1, P2 {
void showAll(); // additional method (optional)
}
// Class Q implements P12
class Q implements P12 {
public void showA() {
System.out.println("Value of A from P1: " + A);
}
public void showB() {
System.out.println("Value of B from P2: " + B);
}
public void showAll() {
System.out.println("Calling both methods:");
showA();
showB();
}
public static void main(String[] args) {
Q obj = new Q(); // Instantiate class Q
obj.showA(); // Invoke method from P1
obj.showB(); // Invoke method from P2
obj.showAll(); // Invoke additional method
}
}
Sample output
Value of A from P1: 10
Value of B from P2: 20
Calling both methods:
Value of A from P1: 10
Value of B from P2: 20
28 of 43
20. Write an application that illustrates method overriding in the same package and different
packages. Also demonstrate accessibility rules in inside and outside packages?
Here's a complete Java example that illustrates method overriding across packages and
demonstrates accessibility rules for public, protected, default (package-private), and
private access modi ers.
Folder Structure:
MyApp/
│
── pack1/
│ └── Base.java
│
── pack2/
│ └── Derived.java
│
└── MainApp.java
File: pack1/Base.java
package pack1;
public class Base {
public void publicMethod() {
System.out.println("Base: public method");
}
protected void protectedMethod() {
System.out.println("Base: protected method");
}
void defaultMethod() {
System.out.println("Base: default (package-private) method");
}
private void privateMethod() {
System.out.println("Base: private method");
}
// Method to call private method (to demonstrate accessibility)
public void callPrivateMethod() {
privateMethod();
}
public void show() {
System.out.println("Base: show() method");
}
}
fi
29 of 43
File: pack2/Derived.java
package pack2;
import pack1.Base;
public class Derived extends Base {
// Overriding public method
@Override
public void publicMethod() {
System.out.println("Derived: public method overridden");
}
// Overriding protected method
@Override
protected void protectedMethod() {
System.out.println("Derived: protected method overridden");
}
// Cannot override defaultMethod() as it's not accessible in another package
// This method is not overriding anything; just to show we can't access private
// @Override
// private void privateMethod() { }
@Override
public void show() {
System.out.println("Derived: show() method overridden");
}
}
File: MainApp.java
import pack2.Derived;
public class MainApp {
public static void main(String[] args) {
Derived obj = new Derived();
obj.publicMethod(); // Accessible & overridden
obj.protectedMethod(); // Accessible because we're calling from subclass
// obj.defaultMethod(); // Not accessible - di erent package
// obj.privateMethod(); // Not accessible - private
obj.callPrivateMethod(); // Indirect access to private method
obj.show(); // Calls overridden show()
}
}
ff
30 of 43
Compile and Run (in terminal):
javac pack1/Base.java
javac -cp . pack2/Derived.java
javac -cp . MainApp.java
java -cp . MainApp
Sample output
Derived: public method overridden
Derived: protected method overridden
Base: private method
Derived: show() method overridden
31 of 43
21. Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, Circle.
Define one method area()in the abstract class and override this area() in these three subclasses to
calculate for specific object i.e. area() of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle ?
Java Program: Abstract Class with Method Overriding
// Abstract class
abstract class Shape {
abstract void area(); // abstract method
}
// Triangle subclass
class Triangle extends Shape {
double base = 10;
double height = 5;
@Override
void area() {
double result = 0.5 * base * height;
System.out.println("Area of Triangle: " + result);
}
}
// Rectangle subclass
class Rectangle extends Shape {
double length = 8;
double width = 4;
@Override
void area() {
double result = length * width;
System.out.println("Area of Rectangle: " + result);
}
}
// Circle subclass
class Circle extends Shape {
double radius = 7;
@Override
void area() {
double result = Math.PI * radius * radius;
System.out.println("Area of Circle: " + result);
}
}
// Main class
public class MainApp {
public static void main(String[] args) {
Shape t = new Triangle(); // polymorphism
Shape r = new Rectangle();
Shape c = new Circle();
t.area(); // Area of Triangle
r.area(); // Area of Rectangle
c.area(); // Area of Circle
}
32 of 43
Sample output
Area of Triangle: 25.0
Area of Rectangle: 32.0
Area of Circle: 153.93804002589985
33 of 43
22. Write a program in Java to demonstrate implementation of multiple inheritance using
interfaces ?
// First interface
interface Printable {
void print();
}
// Second interface
interface Showable {
void show();
}
// Class implementing both interfaces (Multiple Inheritance)
class Demo implements Printable, Showable {
public void print() {
System.out.println("Printing from Printable interface.");
}
public void show() {
System.out.println("Showing from Showable interface.");
}
}
// Main class
public class MainApp {
public static void main(String[] args) {
Demo obj = new Demo();
obj.print();
obj.show();
}
}
Sample output
Printing from Printable interface.
Showing from Showable interface.
34 of 43
23. Write a program in Java to demonstrate use of nal class ?
// Final class
nal class MyFinalClass {
void display() {
System.out.println("This is a nal class.");
}
}
// Uncommenting the below code will cause a compile-time error
// class SubClass extends MyFinalClass {
// void anotherMethod() {
// System.out.println("Trying to inherit nal class.");
// }
// }
public class MainApp {
public static void main(String[] args) {
MyFinalClass obj = new MyFinalClass();
obj.display();
}
}
Sample output
This is a nal class.
fi
fi
fi
fi
fi
35 of 43
24. Write a program in Java to develop user defined exception for ‘Divide by Zero' error ?
// User-de ned exception class
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
// Main class
public class MainApp {
// Method to perform division
static int divide(int numerator, int denominator) throws DivideByZeroException {
if (denominator == 0) {
throw new DivideByZeroException("Cannot divide by zero!");
}
return numerator / denominator;
}
public static void main(String[] args) {
int num = 10;
int den = 0;
try {
int result = divide(num, den);
System.out.println("Result: " + result);
} catch (DivideByZeroException e) {
System.out.println("Exception Caught: " + e.getMessage());
}
}
}
Sample output
Exception Caught: Cannot divide by zero!
fi
36 of 43
25. Write a program in Java to demonstrate multiple try block and multiple catch exception ?
public class MainApp {
public static void main(String[] args) {
// First try-catch block
try {
int[] arr = new int[5];
arr[5] = 10; // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
// Second try-catch block
try {
int a = 10, b = 0;
int result = a / b; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
// Third try-catch with multiple catch options
try {
String s = null;
System.out.println(s.length()); // NullPointerException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException");
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught General Exception");
}
System.out.println("Program continues after exception handling...");
}
}
Sample output
Caught ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Caught ArithmeticException: / by zero
Caught NullPointerException: Cannot invoke "String.length()" because "s" is null
Program continues after exception handling...
37 of 43
26. Write an small application in Java to develop Banking Application in which user deposits the
amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs 300.00 and it throws exception
"Not Sufficient Fund” when user withdraws Rs. 500 thereafter ?
// Custom Exception for insu cient funds
class NotSu cientFundException extends Exception {
public NotSu cientFundException(String message) {
super(message);
}
}
// BankAccount class
class BankAccount {
private double balance;
public BankAccount(double initialAmount) {
this.balance = initialAmount;
}
public void withdraw(double amount) throws NotSu cientFundException {
if (amount > balance) {
throw new NotSu cientFundException("Not Su cient Fund. Available balance: ₹" +
balance);
}
balance -= amount;
System.out.println("Withdrawn: ₹" + amount + " | Remaining Balance: ₹" + balance);
}
public double getBalance() {
return balance;
}
}
// Main application class
public class MainApp {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.00); // Deposit ₹1000
try {
account.withdraw(400.00); // Successful
account.withdraw(300.00); // Successful
account.withdraw(500.00); // Should throw exception
} catch (NotSu cientFundException e) {
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Final Balance: ₹" + account.getBalance());
}
}
ffi
ffi
ffi
ffi
ffi
ffi
ffi
38 of 43
Sample Output
Withdrawn: ₹400.0 | Remaining Balance: ₹600.0
Withdrawn: ₹300.0 | Remaining Balance: ₹300.0
Exception: Not Su cient Fund. Available balance: ₹300.0
Final Balance: ₹300.0
ffi
39 of 43
27. Write a program that executes two threads. One thread displays “Thread1” every 2,000
milliseconds, and the other displays “Thread2” every 4,000 milliseconds. Create the threads by
extending the Thread class ?
// Thread1 class
class Thread1 extends Thread {
public void run() {
try {
while (true) {
System.out.println("Thread1");
Thread.sleep(2000); // 2 seconds
}
} catch (InterruptedException e) {
System.out.println("Thread1 interrupted");
}
}
}
// Thread2 class
class Thread2 extends Thread {
public void run() {
try {
while (true) {
System.out.println("Thread2");
Thread.sleep(4000); // 4 seconds
}
} catch (InterruptedException e) {
System.out.println("Thread2 interrupted");
}
}
}
Sample Output (First few seconds)
Thread1
Thread2
Thread1
Thread1
Thread2
Thread1
...
40 of 43
28. Write a program that executes two threads. One thread will print the even numbers and
the another thread will print odd numbers from 1 to 50.
// Thread for printing even numbers
class EvenThread extends Thread {
public void run() {
for (int i = 1; i <= 50; i++) {
if (i % 2 == 0) {
System.out.println("Even: " + i);
try {
Thread.sleep(100); // Sleep to allow interleaving
} catch (InterruptedException e) {
System.out.println("EvenThread interrupted");
}
}
}
}
}
// Thread for printing odd numbers
class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 50; i++) {
if (i % 2 != 0) {
System.out.println("Odd: " + i);
try {
Thread.sleep(100); // Sleep to allow interleaving
} catch (InterruptedException e) {
System.out.println("OddThread interrupted");
}
}
}
}
}
// Main class
public class MainApp {
public static void main(String[] args) {
EvenThread even = new EvenThread();
OddThread odd = new OddThread();
even.start();
odd.start();
}
}
Sample Output (interleaved):
Odd: 1
Even: 2
Odd: 3
Even: 4
Odd: 5
Even: 6
...
Odd: 49
Even: 50
41 of 43
29. Write a program in Java to demonstrate use of synchronization of threads when multiple
threads are trying to update common variable.
// Shared resource class
class Counter {
int count = 0;
// Synchronized method to ensure only one thread updates at a time
synchronized void increment() {
count++;
}
}
// Thread class
class MyThread extends Thread {
Counter counter;
MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
// Main class
public class MainApp {
public static void main(String[] args) {
Counter counter = new Counter();
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
t1.start();
t2.start();
// Wait for both threads to nish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
// Final count should be 2000
System.out.println("Final Count: " + counter.count);
}
}
fi
42 of 43
Sample output
Final Count: 2000
43 of 43
30. Write a program in Java to create, write, modify, read operations on a text file ?
import java.io.*;
public class FileOperations {
public static void main(String[] args) {
String lename = "example.txt";
// 1. Create and Write to the le
try (FileWriter writer = new FileWriter( lename)) {
writer.write("This is the original content.\n");
System.out.println("File created and written successfully.");
} catch (IOException e) {
System.out.println("Error writing to le: " + e.getMessage());
}
// 2. Append (Modify) the le
try (FileWriter writer = new FileWriter( lename, true)) {
writer.write("This line is appended to the le.\n");
System.out.println("File modi ed (appended) successfully.");
} catch (IOException e) {
System.out.println("Error appending to le: " + e.getMessage());
}
// 3. Read from the le
System.out.println("Reading from the le:");
try (Bu eredReader reader = new Bu eredReader(new FileReader( lename))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading le: " + e.getMessage());
}
}
}
Sample output
File created and written successfully.
File modi ed (appended) successfully.
Reading from the le:
This is the original content.
This line is appended to the le.
fi
fi
ff
fi
fi
fi
fi
fi
fi
fi
ff
fi
fi
fi
fi
fi
fi
fi