0% found this document useful (0 votes)
2 views70 pages

Java Program to Sort Array Halves

Uploaded by

suvrayanghosh289
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views70 pages

Java Program to Sort Array Halves

Uploaded by

suvrayanghosh289
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Sort Half Ascending, Half Descending

Problem Statement
Write a Java program that sorts the first half of the elements in an array in ascending order
and the remaining half in descending order.

Theory
This problem requires manipulating an array by sorting its two distinct halves differently. The
core concept involves using a sorting algorithm, such as [Link]() in Java, on a specific
part of the array. The [Link]() method sorts a range of elements when provided with a
starting and ending index. To sort the second half in descending order, you can first sort it in
ascending order and then reverse the elements. A more direct approach for the descending
part is to use a simple loop that swaps elements from the beginning and end of that specific
half until they meet in the middle, effectively reversing the sorted ascending order.

Algorithm
1. Initialize Array: Create an integer array with an even number of elements.

2. Determine Midpoint: Find the middle index of the array by dividing its length by 2.

3. Sort First Half: Use [Link]() to sort the elements from the beginning of the array
(index 0) up to the midpoint in ascending order.

4. Sort Second Half: Use [Link]() to sort the elements from the midpoint to the end
of the array. This will sort the second half in ascending order.

5. Reverse Second Half: Implement a loop to reverse the elements of the second half.
This loop will iterate from the midpoint up to the end, swapping the first element of
this section with the last, the second with the second-to-last, and so on.

6. Print Result: Display the final array to show the sorted halves.

Source Code
import [Link];

public class HalfSort {

public static void main(String[] args) {

int[] arr = {10, 5, 2, 8, 3, 9, 6, 1};

Page | 1
[Link]("Original array: " +
[Link](arr));

// Get the length of the array and find the midpoint.

int n = [Link];

int mid = n / 2;

// Sort the first half in ascending order.

[Link](arr, 0, mid);

// Sort the second half in ascending order first.

[Link](arr, mid, n);

// Reverse the second half to make it descending.

int start = mid;

int end = n - 1;

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

[Link]("Array with first half ascending and


second half descending: " + [Link](arr));

Output
Original array: [10, 5, 2, 8, 3, 9, 6, 1]

Page | 2
Array with first half ascending and second half descending: [2, 3,
5, 8, 10, 9, 6, 1]

Discussion
This program provides an efficient solution to the problem by leveraging Java's built-in
[Link]() method. The use of [Link](arr, fromIndex, toIndex) is crucial, as it allows
for sorting a specific portion of the array without affecting the other elements. The final step
of reversing the second half is a straightforward and common technique for achieving a
descending sort after an initial ascending sort. It's important to note that this approach
assumes the array has an even number of elements, as the problem statement implies a direct
split into two halves. If the array had an odd number of elements, the definition of "half"
would need to be clarified (e.g., should the middle element be part of the first or second
half?).

Page | 3
2. 2D Matrix with Row and Column Minimums

Problem Statement
Write a Java program that accepts a 2D matrix (a 2-dimensional array) and then prints the matrix
along with the minimum value for each row and the minimum value for each column.

Theory
A 2D matrix is a grid of numbers organized into rows and columns. To find the minimum value in
each row, you can iterate through each row individually and keep track of the smallest element found
so far. Similarly, to find the minimum value in each column, you need to iterate through the columns.

Algorithm
1. Initialize Matrix: Create a 2D integer array and populate it with values.

2. Print Matrix: Use nested loops to iterate through the matrix and print each element,
formatting it to look like a grid.

3. Calculate and Print Row Minimums:

o Create an array to store the minimums of each row.

o Iterate through each row of the matrix.

o For each row, initialize a variable minRow with the first element of that row.

o Iterate through the remaining elements of the current row, comparing each element
with minRow.

o If an element is smaller than minRow, update minRow to that value.

o After checking all elements in the row, store minRow in the row minimums array and
print it.

4. Calculate and Print Column Minimums:

o Create an array to store the minimums of each column.

o Iterate through each column of the matrix.

o For each column, initialize a variable minCol with the first element of that column.

o Iterate through the remaining elements of the current column, comparing each
element with minCol.

o If an element is smaller than minCol, update minCol to that value.

Source Code
import [Link];

public class MatrixMin {

public static void main(String[] args) {

int[][] matrix = {

Page | 4
{3, 5, 2},

{8, 4, 1},

{7, 6, 9}

};

// Print the matrix

[Link]("Original Matrix:");

for (int i = 0; i < [Link]; i++) {

[Link]([Link](matrix[i]));

[Link]();

// Calculate and print row minimums

[Link]("Row Minimums:");

for (int i = 0; i < [Link]; i++) {

int minRow = matrix[i][0];

for (int j = 1; j < matrix[i].length; j++) {

if (matrix[i][j] < minRow) {

minRow = matrix[i][j];

[Link]("Minimum of Row " + (i + 1) + ": " +


minRow);

[Link]();

// Calculate and print column minimums

[Link]("Column Minimums:");

int numRows = [Link];

int numCols = matrix[0].length;

for (int j = 0; j < numCols; j++) {

int minCol = matrix[0][j];

for (int i = 1; i < numRows; i++) {

if (matrix[i][j] < minCol) {

Page | 5
minCol = matrix[i][j];

[Link]("Minimum of Column " + (j + 1) + ": " +


minCol);

Output
Original Matrix:

[3, 5, 2]

[8, 4, 1]

[7, 6, 9]

Row Minimums:

Minimum of Row 1: 2

Minimum of Row 2: 1

Minimum of Row 3: 6

Column Minimums:

Minimum of Column 1: 3

Minimum of Column 2: 4

Minimum of Column 3: 1

Discussion
This program effectively addresses the problem by using two separate logical blocks to find the row
and column minimums. The first block iterates through each row to find its minimum, and the second
block iterates through each column. The key to finding column minimums is to swap the indices in
the nested loop: the outer loop iterates through columns (j), and the inner loop iterates through rows
(i), allowing access to all elements in a single column. The code is clear and demonstrates a
fundamental matrix traversal technique.

Page | 6
3. Delete Consonants from a String

Problem Statement
Write a Java program to delete all consonants from an input string and print the resulting string.

Theory
A string is a sequence of characters. In English, the vowels are 'a', 'e', 'i', 'o', 'u' (and their uppercase
counterparts). All other alphabetic characters are consonants. To solve this problem, you need to
iterate through the input string, character by character. For each character, you check if it is a vowel.
If it is, you keep it; if it is a consonant, you discard it. The result is then a new string composed only
of the original string's vowels and any non-alphabetic characters (like spaces, numbers, or symbols).

Algorithm
1. Get Input String: Take a string as input from the user or initialize a predefined string.

2. Initialize Result String: Create an empty StringBuilder or StringBuffer to build the new
string. Using StringBuilder is more efficient for this task than concatenating String objects
repeatedly.

3. Iterate Through String: Loop through each character of the input string.

4. Check for Vowel: For each character, check if it's a vowel (either lowercase or uppercase). A
simple way is to convert the character to lowercase and then check if it is 'a', 'e', 'i', 'o', or 'u'.

5. Append to Result: If the character is a vowel, append it to the StringBuilder. If the character
is not an alphabet (e.g., a number or a symbol), you can also choose to keep it, as it's not a
consonant.

6. Print Result: Convert the StringBuilder to a String and print the final result.

Source Code
public class RemoveConsonants {

public static void main(String[] args) {

String inputString = "The quick brown fox jumps over the lazy
dog.";

[Link]("Original string: " + inputString);

StringBuilder resultString = new StringBuilder();

// Iterate through each character of the string

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

// Check if the character is a vowel (case-insensitive)

if (isVowel(ch)) {

[Link](ch);

Page | 7
} else if (![Link](ch)) {

// Keep non-alphabetic characters like spaces and


punctuation

[Link](ch);

[Link]("String after removing consonants: " +


[Link]());

// Helper method to check if a character is a vowel

public static boolean isVowel(char ch) {

ch = [Link](ch);

return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==


'u';

Output
Original string: The quick brown fox jumps over the lazy dog.

String after removing consonants: e ui o o u o ee a o.

Discussion
This program uses a straightforward and efficient approach. Instead of creating a new string for every
character that needs to be kept, it utilizes a StringBuilder. This is a best practice in Java for building
strings within a loop because it avoids the creation of numerous intermediate String objects, which
can be memory-intensive. The helper method is Vowel() encapsulates the vowel-checking logic,
making the main for loop cleaner and more readable. The code also correctly handles non-alphabetic
characters by preserving them in the output, which is a reasonable interpretation of the problem
statement "delete all consonants".

Page | 8
4. MyPoint Class and TestMyPoint Driver

Problem Statement
Create a class named MyPoint to model a 2D point with x and y integer coordinates. The class should
include:

● A default constructor to create a point at (0, 0).

● An overloaded constructor to create a point with given x and y coordinates.

● Methods to set and get the coordinates: setXY() and getXY().

● A toString() method to return a string description in the format "(x,y)".

● A distance(int x, int y) method to calculate the distance from this point to another point at (x,
y).

Also, write a test driver class named TestMyPoint to test all the public methods of MyPoint.

Theory
This problem is an exercise in Object-Oriented Programming (OOP), specifically focusing on class
design and method implementation. The MyPoint class encapsulates the data (coordinates) and
behavior (methods like distance, getXY, etc.) of a 2D point.

● Constructors: Used to initialize the state of an object. The default constructor provides a
standard starting point, while the overloaded constructor allows for custom initialization.

● Encapsulation: The instance variables (x and y) are hidden from direct external access, and
their values are manipulated through public methods (setXY, getXY), which is a core
principle of OOP.

● toString() method: A standard Java convention that provides a string representation of an


object, useful for debugging and printing.

● Distance Formula: The distance between two points (x_1,y_1) and (x_2,y_2) is calculated
using the formula: D=sqrt(x_2−x_1)2+(y_2−y_1)2.

Algorithm
MyPoint Class:

1. Variables: Define two instance variables: int x and int y.

2. Default Constructor: Create a constructor MyPoint() that sets x and y to 0.

3. Overloaded Constructor: Create a constructor MyPoint(int x, int y) that initializes the


instance variables with the provided arguments.

4. setXY(int x, int y): A method that assigns the input x and y values to the instance variables.

5. getXY(): A method that returns the coordinates as a 2-element integer array.

6. toString(): A method that returns a string formatted as "(x,y)".

Page | 9
7. distance(int x, int y): A method that calculates and returns the distance using the formula,
taking another point's coordinates as arguments.

TestMyPoint Class:

1. main method: Create the main method to serve as the test driver.

2. Instantiate Objects: Create MyPoint objects using both constructors.

3. Test Methods: Call each of the public methods (setXY, getXY, toString, distance) on the
created objects and print the results to verify they work correctly.

Source Code
// [Link]

public class MyPoint {

private int x;

private int y;

// Default constructor

public MyPoint() {

this.x = 0;

this.y = 0;

// Overloaded constructor

public MyPoint(int x, int y) {

this.x = x;

this.y = y;

// setXY() method

public void setXY(int x, int y) {

this.x = x;

this.y = y;

// getXY() method

public int[] getXY() {

int[] result = new int[2];

result[0] = this.x;

Page | 10
result[1] = this.y;

return result;

// toString() method

@Override

public String toString() {

return "(" + this.x + "," + this.y + ")";

// distance() method

public double distance(int x, int y) {

int deltaX = this.x - x;

int deltaY = this.y - y;

return [Link](deltaX * deltaX + deltaY * deltaY);

// [Link]

public class TestMyPoint {

public static void main(String[] args) {

// Test default constructor

MyPoint p1 = new MyPoint();

[Link]("Default point: " + p1); // calls toString()


automatically

// Test overloaded constructor and distance

MyPoint p2 = new MyPoint(3, 4);

[Link]("Point p2: " + p2);

[Link]("Distance from p1(0,0) to p2(3,4): " +


[Link]([Link]()[0], [Link]()[1]));

// Test setXY()

[Link](1, 1);

[Link]("New p1 after setXY(): " + p1);

Page | 11
// Test getXY()

int[] p1Coords = [Link]();

[Link]("p1 coordinates via getXY(): (" + p1Coords[0] +


", " + p1Coords[1] + ")");

Output
Default point: (0,0)

Point p2: (3,4)

Distance from p1(0,0) to p2(3,4): 5.0

New p1 after setXY(): (1,1)

p1 coordinates via getXY(): (1, 1)

Discussion
This solution demonstrates the correct implementation of a class and a separate test driver, which is a
common practice in software development. The

MyPoint class is well-encapsulated, with its data (x and y) being private and accessible only through
public methods. This prevents direct modification of the object's state from outside the class. The
TestMyPoint class effectively verifies all the required functionalities, showing how to instantiate
objects, call their methods, and interpret the results. The distance() method correctly applies the
Euclidean distance formula, using [Link]() for the square root calculation.

Page | 12
5. Inheritance: Person, Student, and Staff Classes

Problem Statement
Create a superclass Person with instance variables for name and address. Then, create two subclasses,
Student and Staff, which inherit from Person. The Student class should have program, year, and fees
variables , while the Staff class should have school and pay variables. Implement constructors and
methods to set and display information for each class, including toString() methods that provide a
detailed description. Finally, write a test driver to test all the functionalities.

Theory
This problem is a practical application of inheritance, a fundamental concept in Object-Oriented
Programming (OOP). Inheritance allows a class (the subclass or "child") to inherit properties and
methods from another class (the superclass or "parent"). This promotes code reuse and establishes a
clear "is-a" relationship (e.g., a

Student is a Person, and a Staff is a Person). The problem also involves constructor chaining (using
super() to call the superclass's constructor), method overriding (redefining the toString() method in
the subclasses to provide specific information), and encapsulation (using setter and getter methods).

Algorithm
Person Class:

1. Variables: Declare name (String) and address (String).

2. Constructor: Create a constructor Person(String name, String address) to initialize these


variables.

3. setPerson(String name, String address): A method to update the person's details.

4. toString(): A method to return a string in the format "Person [name=?,address=?]" .

Student Class (inherits from Person):

1. Variables: Declare program (String), year (String), and fees (double).

2. Constructor: Create a constructor Student(String name, String address, String program,


String year, double fees). Use super(name, address) to initialize the Person part of the object.

Source Code
// [Link]

Page | 13
public class Person {

private String name;

private String address;

public Person(String name, String address) { // cite: 27

[Link] = name;

[Link] = address;

public void setPerson(String name, String address) { // cite: 27

[Link] = name;

[Link] = address;

@Override

public String toString() { // cite: 27

return "Person [name=" + name + ", address=" + address + "]"; // cite: 27

// [Link]

public class Student extends Person {

private String program; // cite: 28

private String year; // cite: 28

private double fees; // cite: 28

public Student(String name, String address, String program, String year,


double fees) { // cite:29

super(name, address); // cite: 29

[Link] = program;

[Link] = year;

[Link] = fees;

public void setStudent(String name, String address, String program, String


year, double fees) { // cite: 29

[Link](name, address); // Update Person data

[Link] = program;

[Link] = year;

Page | 14
[Link] = fees;

@Override

public String toString() { // cite: 29 return "Person[name=" + [Link] + ",


address=" + [Link] + ", Program=" + program + ", Year=" + year + ", Fees="
+ fees + "]"; // cite: 29

// [Link]

public class Staff extends Person {

private String school; // cite: 30

private double pay; // cite: 30

public Staff(String name, String address, String school, double pay) { //


cite: 30

super(name, address); // cite: 30

[Link] = school;

[Link] = pay;

public void setStaff(String name, String address, String school, double pay)//
cite: 30

[Link](name, address); // Update Person data

[Link] = school;

[Link] = pay;

@Override

public String toString() { // cite: 30

return "Person[name=" + [Link] + ", address=" + [Link] + ",


School=" + school + ", Pay=" + pay + "]"; // cite: 30

// [Link]

public class TestPerson {

public static void main(String[] args) { // cite: 31

// Test Person class

Page | 15
Person p1 = new Person("John Doe", "123 Main St");

[Link]("Initial Person: " + p1);

[Link]("Jane Doe", "456 Oak Ave");

[Link]("Updated Person: " + p1);

[Link]("\n------------------------\n");

// Test Student class

Student s1 = new Student("Alice", "789 Pine Rd", "Computer Science",


"2024", 5000.0); // cite: 29

[Link]("Initial Student: " + s1);

[Link]("Alice", "101 Cedar Ln", "IT", "2025", 5500.0); // cite: 29

[Link]("Updated Student: " + s1);

[Link]("\n------------------------\n");

// Test Staff class

Staff st1 = new Staff("Bob", "202 Birch Dr", "Tech High", 60000.0); //
cite: 30

[Link]("Initial Staff: " + st1);

[Link]("Bob", "303 Elm Rd", "Tech University", 65000.0); // cite: 30

[Link]("Updated Staff: " + st1);

Page | 16
Output
Initial Person: Person [name=John Doe, address=123 Main St]

Updated Person: Person [name=Jane Doe, address=456 Oak Ave]

------------------------

Initial Student: Person[name=Alice, address=789 Pine Rd, Program=Computer Science,


Year=2024, Fees=5000.0]

Updated Student: Person[name=Alice, address=101 Cedar Ln, Program=IT, Year=2025,


Fees=5500.0]

------------------------

Initial Staff: Person[name=Bob, address=202 Birch Dr, School=Tech High,


Pay=60000.0]

Updated Staff: Person[name=Bob, address=303 Elm Rd, School=Tech University,


Pay=65000.0]

Discussion
This program is an excellent demonstration of polymorphism through inheritance and method
overriding. The

Student and Staff classes inherit the basic properties of a Person but extend them with their own
specific variables and behaviors. The use of

super() in the constructors is crucial for initializing the inherited Person variables correctly.
Furthermore, the overridden toString() methods in the subclasses provide a detailed representation of
each object, showcasing how a single method name can have different implementations depending on
the object's type. This design makes the code modular, reusable, and easy to maintain. The test driver
class effectively verifies that each class and method works as expected, confirming the correctness of
the inheritance hierarchy.

Page | 17
6. Inheritance: Square and Cylinder Classes

Problem Statement
Create a base class Square with an instance variable side. It should have a constructor to initialize the
side and a method getVolume() to calculate and print the volume (of a cube, in this case). Then, create
a derived class Cylinder with a height variable. The Cylinder class should use side from the Square
class as its radius and override the getVolume() method to calculate and print the volume of a
cylinder.

Theory
This problem demonstrates inheritance and method overriding. A Cylinder "is a" geometric shape, but
it's not a Square in a typical sense. The problem uses a less conventional inheritance relationship to
teach the concepts of inheriting properties and overriding methods. The base class Square provides a
side property and a getVolume() method. The derived class Cylinder inherits this side property (and
uses it as radius) and provides its own implementation of the getVolume() method.

Algorithm
Square Class:

1. Variables: Define side: double.

2. Constructor: Initialize side.

3. getVolume(): Calculate side * side * side and print the result. This calculates the volume of a
cube, which is the logical volume for a shape based on a square.

Cylinder Class:

1. Variables: Define height: double.

2. Constructor: Use super() to initialize side (as the radius) and initialize height.

3. getVolume(): Override the method. Calculate the volume of a cylinder using the formula

$V = \\pi \* radius^2 \* height$. Print the result.

Source Code
// [Link]

class Square {

double side; // cite: 32

// Constructor to initialize side

public Square(double side) { // cite: 33

[Link] = side;

Page | 18
// Method to calculate and print volume of a cube

public void getVolume() { // cite: 33

double volume = [Link] * [Link] * [Link];

[Link]("Volume of the cube: " + volume);

// [Link]

class Cylinder extends Square {

double height; // cite: 34

// Constructor to initialize both side (as radius) and height

public Cylinder(double radius, double height) { // cite: 34

super(radius); // The 'side' of the square is used as the 'radius'


of the cylinder

[Link] = height;

// Override the getVolume() method for a cylinder

@Override

public void getVolume() { // cite: 34

double volume = [Link] * [Link] * [Link] * [Link];

[Link]("Volume of the cylinder: " + volume);

// Main class to test the functionality

public class TestShapes {

public static void main(String[] args) {

// Create an object of the base class Square

Page | 19
Square myCube = new Square(5.0);

[Link](); // Prints volume of a cube

[Link]();

// Create an object of the derived class Cylinder

Cylinder myCylinder = new Cylinder(3.0, 7.0);

[Link](); // Prints volume of a cylinder

Output
Volume of the cube: 125.0

Volume of the cylinder: 197.92033717615697

Discussion
This program successfully demonstrates how a subclass can inherit from a base class and provide its
own unique implementation for a method defined in the superclass. The core concept here is
polymorphism through method overriding. Although the Cylinder class uses side as radius, the
getVolume() method is completely different, proving that the method's behavior can change in the
subclass while its signature remains the same. This is a key feature of object-oriented design.

Page | 20
7. Vehicle Engine Interface

Problem Statement
Design a vehicle engine with speed and gear properties. Define the functionalities speedUp(value) and
changeGear(value) in an interface. The class implementing this interface must implement all the
methods.

Theory
An interface in Java is a blueprint for a class. It contains a set of abstract methods that a class must
implement. This ensures that any class that "implements" the interface will provide specific, required
functionalities. This is a core concept of polymorphism and is used to define a contract for behavior.
By defining engine functionalities in an interface, you ensure that any type of vehicle (e.g., a car, a
truck) that uses this engine will have the speedUp and changeGear methods.

Algorithm

1. Define Interface: Create an interface named Engine with two abstract methods: speedUp(int
value) and changeGear(int value).

2. Implement Interface: Create a class, for example, Vehicle, that implements the Engine
interface.

3. Instance Variables: In the Vehicle class, define int speed and int gear.

4. Implement Methods: Provide concrete implementations for both speedUp and changeGear
methods within the Vehicle class.

o speedUp(value): Increase the speed by the given value.

o changeGear(value): Update the gear to the given value.

5. Test: In a main method, create a Vehicle object, call its methods to change the speed and gear,
and print the values to show the changes.

Source Code
// [Link] (Interface)

interface Engine {

void speedUp(int value); // cite: 36

void changeGear(int value); // cite: 36

// [Link] (Class implementing the interface)

class Vehicle implements Engine {

int speed; // cite: 35

int gear; // cite: 35

// Implement the speedUp method from the interface

Page | 21
@Override

public void speedUp(int value) {

[Link] += value;

[Link]("Speed increased. Current speed: " +


[Link]);

// Implement the changeGear method from the interface

@Override

public void changeGear(int value) {

[Link] = value;

[Link]("Gear changed. Current gear: " + [Link]);

// [Link] (Main class)

public class TestVehicle {

public static void main(String[] args) {

Vehicle myCar = new Vehicle();

[Link] = 0;

[Link] = 0;

[Link]("Initial State:");

[Link]("Speed: " + [Link] + ", Gear: " +


[Link]);

[Link]("\nExecuting functionalities:");

[Link](20);

[Link](2);

[Link](30);

[Link](4);

Page | 22
Output

Initial State:

Speed: 0, Gear: 0

Executing functionalities:

Speed increased. Current speed: 20

Gear changed. Current gear: 2

Speed increased. Current speed: 50

Gear changed. Current gear: 4

Discussion
This program effectively uses an interface to enforce a specific structure on the Vehicle class. The

Engine interface acts as a contract, guaranteeing that any class implementing it will have the speedUp
and changeGear methods. This design is excellent for creating a flexible and scalable system where
multiple vehicle types can implement the same engine behavior. It promotes

loose coupling, allowing you to change the Vehicle class's internal implementation without affecting
other parts of the program, as long as the interface contract is met.

Page | 23
8. Exception Handling: ArrayIndexOutOfBoundsException and ArithmeticException

Problem Statement
Write a Java program that handles both ArrayIndexOutOfBoundsException and ArithmeticException.

Theory
Exception handling is a crucial part of robust Java programming. It allows you to anticipate and
manage runtime errors gracefully, preventing your program from crashing.
ArrayIndexOutOfBoundsException occurs when you try to access an array element using an index
that is outside the valid range (e.g., negative or greater than or equal to the array's size).
ArithmeticException occurs when an illegal mathematical operation is performed, most commonly
division by zero. A try-catch-finally block is used to handle exceptions.

Algorithm

1. try block: Enclose the potentially problematic code within a try block.

2. ArrayIndexOutOfBoundsException: In this block, attempt to access an array element using an


invalid index.

3. ArithmeticException: Also in the try block, attempt to perform a division by zero.

4. catch blocks: Follow the try block with two separate catch blocks.

o The first catch block should be for ArrayIndexOutOfBoundsException, where you


can print an informative message.

o The second catch block should be for ArithmeticException, where you can print an
appropriate error message.

5. finally block (optional): Add a finally block to execute code that must run regardless of
whether an exception occurred or was handled (e.g., resource cleanup).

Source Code

public class ExceptionHandlingDemo {

public static void main(String[] args) { // cite: 38

[Link]("--- Demonstrating
ArrayIndexOutOfBoundsException ---");

try {

int[] numbers = {1, 2, 3};

[Link]("Trying to access an invalid index...");

[Link](numbers[10]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Caught an exception: " + [Link]());

Page | 24
[Link]("Error: You are trying to access an array
index that does not exist.");

[Link]("\n--- Demonstrating ArithmeticException ---");

try {

int a = 10;

int b = 0;

[Link]("Trying to divide by zero...");

int result = a / b; // This will throw ArithmeticException

[Link]("Result: " + result); // This line will not


be executed

} catch (ArithmeticException e) {

[Link]("Caught an exception: " + [Link]());

[Link]("Error: Division by zero is not allowed.");

Output
--- Demonstrating ArrayIndexOutOfBoundsException ---

Trying to access an invalid index...

Caught an exception: Index 10 out of bounds for length 3

Error: You are trying to access an array index that does not exist.

--- Demonstrating ArithmeticException ---

Trying to divide by zero...

Caught an exception: / by zero

Error: Division by zero is not allowed.

Discussion
This program provides clear, separate demonstrations of handling two common types of exceptions.
By using two distinct try-catch blocks, the code clearly isolates the two different error scenarios. The
catch blocks not only catch the specific exceptions but also provide meaningful feedback to the user,
which is a key part of good exception handling.

Page | 25
9. JDBC Connectivity: Student Data Management

Problem Statement
Write a Java program that inputs student data (registration number, name, city, contact number) from
the user and inserts it into a Student_info table using JDBC connectivity. The program should also
view all records in a tabular format.

Theory
JDBC (Java Database Connectivity) is a standard Java API that allows Java programs to connect to a
relational database and perform operations like querying, updating, and inserting data. The process
involves several key steps: loading the JDBC driver, establishing a connection, creating a statement
object, executing SQL commands, and processing the results. A PreparedStatement is often used for
INSERT operations to prevent SQL injection and efficiently handle parameterized queries.

Algorithm
1. Load Driver: Load the JDBC driver for the database you're using (e.g., MySQL, Oracle).

2. Establish Connection: Use [Link]() to connect to the database.

3. Input Data: Use a Scanner to get student details (registration number, name, city, contact
number) from the user.

4. Insert Data:

o Create a PreparedStatement with an INSERT SQL query for the Student_info table.

o Use the set methods (setString, setInt, etc.) to bind the user's input to the query
parameters (?).

o Execute the statement using executeUpdate().

5. View Records:

o Create a Statement object.

o Execute a SELECT * FROM Student_info query using executeQuery().

o Iterate through the ResultSet to retrieve each row of data.

o Print the data for each student in a well-formatted, tabular manner.

6. Close Resources: Ensure all resources (ResultSet, Statement, Connection) are closed in a
finally block to prevent resource leaks.

Source Code
import [Link].*;

import [Link];

public class StudentDataJDBC {

// JDBC URL, user, and password for your database

Page | 26
static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database_name";

static final String USER = "your_username";

static final String PASS = "your_password";

public static void main(String[] args) {

Connection conn = null;

PreparedStatement pstmt = null;

Statement stmt = null;

Scanner scanner = new Scanner([Link]);

try {

// Register JDBC driver (for older versions of JDBC)

// [Link]("[Link]");

// Open a connection

conn = [Link](DB_URL, USER, PASS);

[Link]("Connection established successfully.");

// 1. Insert student data from user input

[Link]("\nEnter Student Details:");

[Link]("Reg No: ");

String regNo = [Link](); // Assuming a String for


Regno for simplicity

[Link]("Name: ");

String sName = [Link]();

[Link]("City: ");

String city = [Link]();

[Link]("Contact No: ");

String contactNo = [Link]();

String sql = "INSERT INTO Student_info (Regno, Sname, City,


ContactNo) VALUES (?, ?, ?, ?)"; // cite: 39

pstmt = [Link](sql);

[Link](1, regNo);

[Link](2, sName);

Page | 27
[Link](3, city);

[Link](4, contactNo);

int rowsAffected = [Link]();

[Link](rowsAffected + " record(s) inserted


successfully.");

// 2. View all records in a tabular format

[Link]("\n--- Student Records ---");

stmt = [Link]();

String selectSql = "SELECT Regno, Sname, City, ContactNo FROM


Student_info"; // cite: 40

ResultSet rs = [Link](selectSql);

// Print table header

[Link]("%-10s %-20s %-15s %-15s\n", "Reg No",


"Name", "City", "Contact No");

[Link]("------------------------------------------
------------------------");

// Loop through the result set and print data

while ([Link]()) {

[Link]("%-10s %-20s %-15s %-15s\n",

[Link]("Regno"),

[Link]("Sname"),

[Link]("City"),

[Link]("ContactNo"));

[Link]();

} catch (SQLException se) {

[Link]();

} finally {

try {

if (pstmt != null) [Link]();

} catch (SQLException se2) { }

try {

Page | 28
if (stmt != null) [Link]();

} catch (SQLException se3) { }

try {

if (conn != null) [Link]();

} catch (SQLException se) {

[Link]();

if (scanner != null) {

[Link]();

NOTE: This code requires a MySQL JDBC driver and a pre-existing Student_info table with
columns: Regno, Sname, City, and ContactNo.

Page | 29
Output

Connection established successfully.

Enter Student Details:

Reg No: 123

Name: Alice

City: New York

Contact No: 555-1234

1 record(s) inserted successfully.

--- Student Records ---

Reg No Name City Contact No

------------------------------------------------------------------

123 Alice New York 555-1234

...

Discussion

This program provides a clear example of a complete JDBC workflow for data management. It
correctly uses a PreparedStatement for a secure and efficient INSERT operation, which is a best
practice. It also demonstrates how to retrieve and display data from the database using a Statement
and ResultSet. The use of printf for formatted output ensures the records are presented in a clean,
tabular format. The try-catch-finally block structure is essential for robust code, guaranteeing that
database resources are released even if an error occurs.

Page | 30
10. Remove a Specific Element from an Array

Problem Statement
Write a Java program to remove a specific element from an array.

Theory
Arrays in Java have a fixed size, so you can't actually "remove" an element. Instead, you create a new
array of a smaller size and copy all the elements from the old array, except for the one you want to
remove. A common approach is to shift elements to the left, effectively overwriting the element to be
removed, and then creating a new, smaller array from the updated list.

Algorithm
1. Initialize Array: Start with an integer array.

2. Specify Element: Define the element you want to remove.

3. Find Element: Iterate through the array to find the index of the element to be removed.

4. Create New Array: Create a new array with a size one less than the original.

5. Copy Elements: Use a loop to copy elements from the original array to the new one. Use a
conditional statement to skip the element at the specified index.

6. Print Result: Print the new array to show the removed element.

Source Code
import [Link];

public class RemoveElement {

public static void main(String[] args) { // cite: 41

int[] originalArray = {10, 20, 30, 40, 50};

int elementToRemove = 30;

int indexToRemove = -1;

[Link]("Original Array: " +


[Link](originalArray));

// Find the index of the element to be removed

for (int i = 0; i < [Link]; i++) {

if (originalArray[i] == elementToRemove) {

indexToRemove = i;

break;

Page | 31
// Check if the element was found

if (indexToRemove == -1) {

[Link]("Element " + elementToRemove + " not found


in the array.");

return;

// Create a new array with a size one less than the original

int[] newArray = new int[[Link] - 1];

// Copy elements, skipping the one to be removed

for (int i = 0, j = 0; i < [Link]; i++) {

if (i != indexToRemove) {

newArray[j++] = originalArray[i];

[Link]("Array after removing " + elementToRemove + ":


" + [Link](newArray));

Output
Original Array: [10, 20, 30, 40, 50]

Array after removing 30: [10, 20, 40, 50]

Discussion
The program correctly demonstrates how to "remove" an element from a fixed-size array in Java by
creating a new array. The algorithm is straightforward: find the element, then create a new array and
copy everything over except for the element you want to get rid of. This approach is memory-
intensive for large arrays but is the standard method for this task in Java when using native arrays. For
dynamic resizing, ArrayList would be a more suitable data structure.

Page | 32
11. Insert an Element into an Array

Problem Statement
Write a Java program to insert an element at a specific position in an array.

Theory
Like removing an element, inserting an element into a Java array requires creating a new, larger
array. Since arrays have a fixed size, you cannot simply add an element. The process involves
shifting existing elements to make space for the new element at the desired position and then copying
all elements into a new array.

Algorithm
1. Initialize Array: Start with an integer array.

2. Specify Element & Position: Define the element to be inserted and the specific index where
it should be placed.

3. Create New Array: Create a new array with a size one greater than the original.

4. Copy and Insert: Iterate through the original array and copy elements to the new array.

o Elements before the insertion point are copied directly.

o At the insertion point, the new element is inserted.

o Elements from the insertion point onwards are shifted one position to the right.

5. Print Result: Print the new array to show the element at the specified position.

Source Code
import [Link];

public class InsertElement {

public static void main(String[] args) { // cite: 42

int[] originalArray = {10, 20, 40, 50};

int elementToInsert = 30;

int positionToInsert = 2; // Index where the element will be


inserted

[Link]("Original Array: " +


[Link](originalArray));

// Create a new array with an increased size

int[] newArray = new int[[Link] + 1];

// Copy elements before the insertion point

Page | 33
for (int i = 0; i < positionToInsert; i++) {

newArray[i] = originalArray[i];

// Insert the new element at the specified position

newArray[positionToInsert] = elementToInsert;

// Shift and copy the remaining elements

for (int i = positionToInsert; i < [Link]; i++) {

newArray[i + 1] = originalArray[i];

[Link]("Array after inserting " + elementToInsert + "


at position " + positionToInsert + ": " + [Link](newArray));

Output
Original Array: [10, 20, 40, 50]

Array after inserting 30 at position 2: [10, 20, 30, 40, 50]

Discussion
This program accurately demonstrates the common method for inserting an element into a fixed-size
array in Java. The key is creating a new array of the correct size and then carefully managing the
indices during the copying process. The first loop handles elements before the new element, the single
line inserts the new element, and the second loop handles the elements that must be shifted to make
space. This approach is effective and a fundamental operation for array manipulation.

Page | 34
Problem Statement 12
Write a Java program to find all pairs of elements in an array whose sum is equal to a specified
number.

Theory

● The problem requires searching for pairs (arr[i],


arr[j]) such that:

● This is a classic array problem often seen in coding interviews.

● Two main approaches:

1. Brute Force (O(n²)) → Check all pairs.

2. Hashing (O(n)) → Use a HashSet to store visited elements and check complement.

We’ll implement the brute force method since it’s simple and matches academic assignments.

Algorithm
1. Input array size and elements.

2. Input the target sum.

3. Use two nested loops:

o Outer loop: i = 0 to n-1.

o Inner loop: j = i+1 to n-1.

o If arr[i] + arr[j] == target, print the pair.

4. If no pairs found, print appropriate message.

Source Code
import [Link];

public class PairSum {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input size

[Link]("Enter size of array: ");

int n = [Link]();

int[] arr = new int[n];

// Input elements

Page | 35
[Link]("Enter elements:");

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

// Input target sum

[Link]("Enter target sum: ");

int target = [Link]();

// Find pairs

boolean found = false;

[Link]("Pairs with sum " + target + ":");

for (int i = 0; i < n; i++) {

for (int j = i + 1; j < n; j++) {

if (arr[i] + arr[j] == target) {

[Link](arr[i] + " + " + arr[j] + " = " +


target);

found = true;

if (!found) {

[Link]("No pairs found.");

Page | 36
Sample Input
Enter size of array: 6

Enter elements:

2 4 3 5 7 8

Enter target sum: 9

Sample Output
Pairs with sum 9:

2 + 7 = 9

4 + 5 = 9

Discussion
● The program checks all pairs and prints those that match the target sum.

● Complexity:

o Time = O(n²) (nested loops).

o Space = O(1).

● Optimized Approach:

o Use a HashSet → Time = O(n).

o But for assignments, the brute force approach is usually expected.

● Edge cases:

o If array has duplicates, multiple pairs may repeat.

o If no pair exists, program clearly mentions it.

Page | 37
Problem Statement 13
Write a Java program to remove the duplicate elements of a given array and return the new length of
that array.

Theory
● Arrays may contain duplicate elements.

● To remove duplicates:

1. Sort the array (duplicates will be adjacent).

2. Traverse the array and copy only unique elements to a new array.

3. Return the size of the new array (number of unique elements).

This is similar to the "remove duplicates" problem in many coding platforms.

Algorithm
1. Input array size and elements.

2. Sort the array.

3. Initialize a new array temp.

4. Traverse the array:

o If current element ≠ next element → copy it to temp.

5. Copy the last element as it’s always unique at the end.

6. Print new array without duplicates.

7. Return the new length.

Source Code
import [Link];

import [Link];

public class RemoveDuplicates {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input size

[Link]("Enter size of array: ");

Page | 38
int n = [Link]();

int[] arr = new int[n];

// Input elements

[Link]("Enter elements:");

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

// Sort the array

[Link](arr);

// Remove duplicates

int[] temp = new int[n];

int j = 0;

for (int i = 0; i < n - 1; i++) {

if (arr[i] != arr[i + 1]) {

temp[j++] = arr[i];

temp[j++] = arr[n - 1]; // add last element

// Print result

[Link]("Array after removing duplicates:");

for (int i = 0; i < j; i++) {

[Link](temp[i] + " ");

[Link]("\nNew length of array: " + j);

Page | 39
Sample Input
Enter size of array: 8

Enter elements:

4 5 9 4 2 2 8 9

Sample Output
Array after removing duplicates:

2 4 5 8 9

New length of array: 5

Discussion
● Sorting ensures duplicates are adjacent.

● Unique elements are copied into temp.

● Complexity:

o Sorting → O(n log n)

o Traversal → O(n)

o Overall → O(n log n)

● Alternative: Use HashSet (simpler, O(n)) but output order is not guaranteed.

● Works well for assignments requiring array manipulation.

Page | 40
Problem Statement 14

Write a Java program to find the length of the longest consecutive elements sequence from a given
unsorted array of integers.

Example:
Input: [49, 1, 3, 200, 2, 4, 70, 5]
Output: 5 (since the longest sequence is [1, 2, 3, 4, 5]).

Theory
● A consecutive sequence means numbers appearing one after another in natural order.

o Example: [1, 2, 3, 4] → length = 4.

● The challenge: The array is unsorted.

Approaches:

1. Sorting Approach (O(n log n))

o Sort the array.

o Traverse and count consecutive runs.

o Track the maximum length.

2. HashSet Approach (O(n))

o Insert all numbers in a HashSet.

o For each number, check if it is the start of a sequence (num-1 not in set).

o Extend sequence by checking (num+1, num+2, …).

o Track the maximum length.

We’ll use the HashSet approach (efficient and elegant).

Algorithm
1. Input array elements.

2. Store all elements in a HashSet (fast lookup).

3. For each element:

o If (num-1) is not in set → it’s the start of a sequence.

o Count how many consecutive numbers exist.

o Update maximum length.

4. Print the maximum length.

Source Code
import [Link];

Page | 41
import [Link];

public class LongestConsecutive {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input size

[Link]("Enter size of array: ");

int n = [Link]();

int[] arr = new int[n];

// Input elements

[Link]("Enter elements:");

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

// Use HashSet for fast lookup

HashSet<Integer> set = new HashSet<>();

for (int num : arr) {

[Link](num);

int longest = 0;

// Check each number if it starts a sequence

for (int num : set) {

if (![Link](num - 1)) { // starting point

int currentNum = num;

int length = 1;

while ([Link](currentNum + 1)) {

currentNum++;

Page | 42
length++;

longest = [Link](longest, length);

[Link]("Length of longest consecutive sequence: " +


longest);

Sample Input
Enter size of array: 8

Enter elements:

49 1 3 200 2 4 70 5

Sample Output
Length of longest consecutive sequence: 5

Discussion
● Efficient HashSet-based solution avoids sorting.

● Time Complexity:

o O(n) for inserting into set.

o O(n) for traversal.

o Overall → O(n).

● Space Complexity: O(n) for HashSet.

● Works even if array has duplicates (set handles them).

Page | 43
Problem Statement 15
Write a Java program to compare two strings lexicographically.

Theory
● Lexicographical order is dictionary order (like alphabet order).

● Java provides:

o compareTo(String str) method →

▪ Returns 0 if equal.

▪ Returns < 0 if calling string is smaller.

▪ Returns > 0 if calling string is larger.

Example:

● "apple".compareTo("banana") → negative (since "apple" comes before "banana").

● "dog".compareTo("cat") → positive (since "dog" comes after "cat").

● "hello".compareTo("hello") → 0.

Algorithm
1. Read two strings.

2. Use compareTo() method.

3. If result = 0 → strings are equal.

4. If result < 0 → first string is smaller.

5. If result > 0 → first string is larger.

Source Code
import [Link];

public class StringCompare {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input two strings

[Link]("Enter first string: ");

String str1 = [Link]();

Page | 44
[Link]("Enter second string: ");

String str2 = [Link]();

// Compare lexicographically

int result = [Link](str2);

if (result == 0) {

[Link]("Strings are equal.");

} else if (result < 0) {

[Link](str1 + " comes before " + str2 + "


lexicographically.");

} else {

[Link](str1 + " comes after " + str2 + "


lexicographically.");

Sample Input
Enter first string: apple

Enter second string: banana

Sample Output
apple comes before banana lexicographically.

Discussion
● Uses Java’s built-in compareTo() method.

● Complexity: O(n) where n = length of shorter string (comparison goes char by char).

● Handles both uppercase and lowercase (based on ASCII/Unicode values).

● "Apple" and "apple" are different since Java compares case-sensitive.

o "Apple".compareTo("apple") → negative (since 'A' < 'a').

Problem Statement 16

Page | 45
Write a Java program to find whether a region in the current string matches a region in another
string.

Sample Output :

str1[0 - 7] == str2[28 - 35]? true

str1[9 - 15] == str2[9 - 15]? false

Theory
● Java provides the method regionMatches() in the String class.

● Syntax:

boolean regionMatches(int toffset, String other, int ooffset, int len)

● Parameters:

o toffset → starting index in first string.

o other → second string.

o ooffset → starting index in second string.

o len → number of characters to compare.

● Returns true if both regions match, else false.

Example:

String s1 = "HelloWorld";

String s2 = "SayHelloWorldNow";

[Link](0, s2, 3, 5) → true ("Hello" vs "Hello")

Algorithm
1. Read two strings from user.

2. Ask user for starting positions and length of substring to compare.

3. Use regionMatches() to check equality.

4. Print result.

Page | 46
Source Code
import [Link];

public class RegionMatch {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input strings

[Link]("Enter first string: ");

String str1 = [Link]();

[Link]("Enter second string: ");

String str2 = [Link]();

// Input positions and length

[Link]("Enter starting index in first string: ");

int start1 = [Link]();

[Link]("Enter starting index in second string: ");

int start2 = [Link]();

[Link]("Enter length of region to compare: ");

int len = [Link]();

// Compare regions

boolean match = [Link](start1, str2, start2, len);

[Link]("str1[" + start1 + " - " + (start1 + len - 1) +


"] == str2[" +

start2 + " - " + (start2 + len - 1) + "]? " +


match);

Page | 47
Sample Input
Enter first string: HelloWorld

Enter second string: SayHelloWorldNow

Enter starting index in first string: 0

Enter starting index in second string: 3

Enter length of region to compare: 5

Sample Output
str1[0 - 4] == str2[3 - 7]? true

Discussion
● Uses regionMatches() to check substring equality without extracting substrings.

● Complexity: O(len) → compares only the specified region.

● Case-sensitive by default, but can be case-insensitive with:

● regionMatches(true, toffset, other, ooffset, len)

● Useful for searching text patterns or validating parts of strings.

Page | 48
Problem Statement 17
Write a Java program to print all permutations of a given string with repetition.

Example:

The given string is: PQR

The permuted strings are:

PPP, PPQ, PPR, RRP, RRQ, RRR ...

Theory
● A permutation with repetition means every position in the output string can be filled with
any of the characters from the input string.

● If input string has n characters and we want permutations of length r, total permutations are:

nrn^rnr

● Here, since r = length of string, total permutations = nnn^nnn.

Example:
For string "PQR" (n = 3), length = 3 →
Total permutations = 33=273^3 = 2733=27.

Algorithm
1. Input the string.

2. Use recursion to generate all permutations:

o Base case → if length = 0, print the string.

o Recursive case → for each character, append it and recurse for remaining length.

3. Print all generated strings.

Source Code
import [Link];

public class PermutationWithRepetition {

// Recursive function

static void generatePermutations(String str, String prefix, int


length) {

if (length == 0) {

[Link](prefix);

Page | 49
return;

for (int i = 0; i < [Link](); i++) {

generatePermutations(str, prefix + [Link](i), length - 1);

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input string

[Link]("Enter a string: ");

String input = [Link]();

[Link]("The given string is: " + input);

[Link]("The permuted strings are:");

generatePermutations(input, "", [Link]());

Page | 50
Sample Input
Enter a string: PQR

Sample Output (Partial)


The given string is: PQR

The permuted strings are:

PPP

PPQ

PPR

PQP

PQQ

PQR

PRP

PRQ

PRR

QPP

QPQ

...

(27 total permutations printed)

Discussion
● This program uses recursion to generate permutations.

● Complexity:

o Time = O(nn)O(n^n)O(nn) where n = string length.

o Space = O(n) for recursion depth.

● For large strings, output grows exponentially.

● Useful for combinatorial problems, password generation, and testing scenarios.

Page | 51
18. Count Words in a String

Problem Statement
Write a Java program to count all words in an input string.

Theory
A simple way to count words is to split the string into an array of words based on a delimiter, such as
a space. The number of elements in the resulting array will then be the word count. The split() method
in Java is perfect for this. It handles multiple spaces between words and leading/trailing spaces
correctly.

Algorithm
1. Get Input String: Take a string as input.

2. Trim Whitespace: Remove leading and trailing whitespace using trim().

3. Split String: Use the split() method with a regular expression "\\s+" to split the string into an
array of words. \s+ means "one or more whitespace characters".

4. Count Words: The length of the resulting array is the word count.

5. Print Result: Display the final word count.

Source Code
import [Link];

public class WordCount {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Input the string:");

String inputString = [Link]();

// Handle empty strings or strings with only whitespace

if ([Link]().isEmpty()) {

[Link]("Number of words in the string: 0");

Page | 52
[Link]();

return;

// Split the string by one or more whitespace characters

String[] words = [Link]().split("\\s+");

[Link]("Number of words in the string: " +


[Link]);

[Link]();

Output
Input the string:

The quick brown fox jumps over the lazy dog.

Number of words in the string: 9

Discussion
This program provides a concise and effective solution using the split() method, a powerful built-in
Java string function. The use of the regular expression "\\s+" is key, as it correctly handles variations
in spacing between words. The initial check for an empty or all-whitespace string adds robustness,
preventing an incorrect count of 1 for an empty string. This approach is simple, readable, and highly
efficient for this task.

Page | 53
19. Create a Box Class with a Constructor Taking an Object as an Argument

Problem Statement
Write a Java program to create a Box class with a parameterized constructor that takes a Box object as
an argument to initialize its length, breadth, and height. Also, create a function volume which returns
the volume of the box and print it in the main method.

Theory
This problem demonstrates the concept of copy constructors in Java. A copy constructor is a special
type of constructor that creates a new object by copying the values of an existing object. This is a
useful technique when you want to create a duplicate of an object without directly referencing the
original. It ensures that changes to the new object do not affect the original object.

Algorithm

1. Box Class:

o Variables: Declare length, breadth, and height as double.

o Parameterized Constructor: Create a constructor Box(double l, double b, double h)


to initialize these variables.

o Copy Constructor: Create a constructor Box(Box ob) that takes a Box object as an
argument and initializes its own variables with the values from the passed object.

o volume() Method: Create a method that returns the volume, calculated as length *
breadth * height.

2. main Method:

o Create a Box object using the standard parameterized constructor.

o Create a second Box object using the copy constructor, passing the first object as an
argument.

o Call the volume() method on both objects and print their volumes to show they are
identical.

Source Code
// [Link]

class Box {

double length;

double breadth;

double height;

Page | 54
// Parameterized constructor

public Box(double length, double breadth, double height) {

[Link] = length;

[Link] = breadth;

[Link] = height;

// Copy constructor

public Box(Box ob) {

[Link] = [Link];

[Link] = [Link];

[Link] = [Link];

// Method to return the volume of the box

public double volume() {

return length * breadth * height;

// Main method to test the Box class

public class TestBox {

public static void main(String[] args) {

// Create an object using the parameterized constructor

Box myBox1 = new Box(10, 20, 15);

// Create an object using the copy constructor

Box myBox2 = new Box(myBox1);

Page | 55
[Link]("Volume of myBox1: " + [Link]());

[Link]("Volume of myBox2 (created with copy


constructor): " + [Link]());

Output
Volume of myBox1: 3000.0

Volume of myBox2 (created with copy constructor): 3000.0

Discussion
This program clearly illustrates the use of a copy constructor. By taking an object as an argument, the
constructor creates a new, independent instance with the same property values as the original. This is
a better practice than simple object assignment (Box myBox2 = myBox1), which would create a
shallow copy where both variables refer to the same object in memory. A copy constructor ensures a
deep copy, providing a new object with its own distinct memory space.

Page | 56
20. Employee Class with Object-Oriented Operations

Problem Statement
Create a Employee class in Java and perform the following operations: a) Create two constructors: a
default constructor and one that takes an object as a parameter to initialize class variables. b) Create a
function calculate() which calculates the Provident Fund (PF) and allowances based on the employee's
salary and returns all values as an object. c) Write a test driver to verify all functionalities.

Theory
This problem expands on the concepts of Object-Oriented Programming (OOP), specifically
focusing on constructors, copy constructors, and encapsulation. The default constructor provides a
standard way to instantiate an object, while the copy constructor allows for creating a new object from
an existing one, ensuring data independence. The calculate() method demonstrates how an object can
encapsulate logic and return a new object containing the results of that logic, which is a powerful
design pattern.

Algorithm
1. Employee Class:

o Variables: Declare salary (double), pf (double), and allowances (double).

o Default Constructor: Initialize salary to 0.0.

o Copy Constructor: Take an Employee object as an argument and copy its salary to
the new object.

o calculate() Method:

▪ This method should not take any arguments.

▪ Calculate pf (e.g., 12% of salary) and allowances (e.g., 10% of salary).

▪ Return the current Employee object itself (this) to demonstrate returning an


object.

2. main Method:

o Create an Employee object using the default constructor.

o Set the salary for this object.

o Call the calculate() method on this object to get the calculated values.

o Print the original salary and the calculated pf and allowances.

o Create a second Employee object using the copy constructor and print its values to
show the copy was successful.

Page | 57
Source Code
// [Link]

class Employee {

double salary;

double pf;

double allowances;

// a) Default constructor

public Employee() {

[Link] = 0.0;

// a) Copy constructor

public Employee(Employee emp) {

[Link] = [Link];

[Link] = [Link];

[Link] = [Link];

// b) Calculate PF and allowances and return the object

public Employee calculate() {

[Link] = [Link] * 0.12; // 12% of salary for PF

[Link] = [Link] * 0.10; // 10% of salary for


allowances

return this;

@Override

public String toString() {

return "Employee [salary=" + salary + ", pf=" + pf + ",


allowances=" + allowances + "]";

// Main class to test the functionality

public class TestEmployee {

Page | 58
public static void main(String[] args) {

// Test with the default constructor

Employee emp1 = new Employee();

[Link] = 50000.0;

[Link]("Employee 1 (before calculation): " +


emp1);

// Calculate and get the updated object

Employee calculatedEmp1 = [Link]();

[Link]("Employee 1 (after calculation): " +


calculatedEmp1);

[Link]("\n--- Testing Copy Constructor ---");

// Create a new employee object using the copy constructor

Employee emp2 = new Employee(emp1);

[Link]("Employee 2 (copy of Employee 1): " + emp2);

Output
Employee 1 (before calculation): Employee [salary=50000.0, pf=0.0,
allowances=0.0]

Employee 1 (after calculation): Employee [salary=50000.0, pf=6000.0,


allowances=5000.0]

--- Testing Copy Constructor ---

Employee 2 (copy of Employee 1): Employee [salary=50000.0, pf=6000.0,


allowances=5000.0]

Discussion
This program successfully implements the specified functionalities, demonstrating practical OOP
principles. The two constructors offer flexible object creation. The calculate() method is a great
example of an instance method that modifies the object's internal state and returns a reference to
itself, making it easy to use in chained method calls. The test driver confirms that the calculations are
correct and that the copy constructor creates a new, independent object with the same state.

Page | 59
21. User-Defined Exception: NegativeSizeException

Problem Statement
Write a Java program to create your own exception named NegativeSizeException whenever negative
values are used to define the size of an array.

Theory
In Java, a custom or user-defined exception is a class that extends either Exception or one of its
subclasses (like RuntimeException). This allows developers to create specific exceptions for their
application's unique error conditions, making the code more readable and manageable. The
NegativeSizeException will be thrown when an array is attempted to be created with a negative size,
which would otherwise result in an NegativeArraySizeException at runtime. By creating a custom
exception, you can handle this specific error more explicitly.

Algorithm
1. Create Custom Exception:

o Define a class named NegativeSizeException.

o It must extend the Exception class.

o Add a constructor that takes a String message and passes it to the superclass
constructor.

2. Main Program:

o Use a Scanner to get an integer from the user, representing the desired array size.

o Use a try-catch block.

o Inside the try block, check if the input value is negative.

o If the value is negative, throw a new NegativeSizeException with a custom error


message.

o If the value is non-negative, create the array and print a success message.

o In the catch block, catch the NegativeSizeException and print its message.

Source Code
import [Link];

// Custom exception class

class NegativeSizeException extends Exception {

Page | 60
public NegativeSizeException(String message) {

super(message);

public class CustomExceptionDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

try {

[Link]("Enter the size of the array: ");

int size = [Link]();

if (size < 0) {

throw new NegativeSizeException("Array size cannot be


negative: " + size);

int[] arr = new int[size];

[Link]("Array of size " + size + " created


successfully.");

} catch (NegativeSizeException e) {

[Link]("Custom Exception Caught: " +


[Link]());

} finally {

[Link]();

Page | 61
Output
Enter the size of the array: -5

Custom Exception Caught: Array size cannot be negative: -5

Or if a valid number is entered:

Enter the size of the array: 5

Array of size 5 created successfully.

Discussion
This program successfully demonstrates how to define and use a custom exception. By extending the
Exception class, NegativeSizeException becomes a checked exception, meaning the compiler forces
the programmer to handle it. This explicit handling in the try-catch block makes the code more robust
and self-documenting. The custom exception provides a clear, domain-specific error message that is
more useful than a generic runtime exception, improving the program's error reporting.

Page | 62
22. Student Class with Object Equality Check

Problem Statement
Create a class Student with the following operations: a) Create a parameterized constructor to
initialize the objects. b) Create a function isEqual() to check whether two objects are equal or not,
which returns a Boolean value and takes two objects as arguments. c) Print the result in the main
method if the objects are equal or not (take variables as your assumption).

Theory
This problem focuses on object comparison in Java. By default, the == operator checks if two object
references point to the same memory location (i.e., they are the same object). However, to check if
two different objects have the same content (same values for their instance variables), you must
define a custom method like isEqual() or override the equals() method inherited from the Object class.
This allows you to define what "equality" means for your specific class.

Algorithm
1. Student Class:

o Variables: Declare instance variables like id (int) and name (String) to represent a
student.

o Parameterized Constructor: Create a constructor that initializes the id and name of


the object.

o isEqual() Method:

▪ This method should be static, as it operates on two objects passed to it, not on
a single instance.

▪ It should take two Student objects as arguments.

▪ It should return true if both objects have the same id and name, and false
otherwise.

2. main Method:

o Create two Student objects.

o Create a third Student object that is a duplicate of one of the first two.

o Call the isEqual() method to compare:

▪ The first two objects (which should be different).

▪ The first object and its duplicate (which should be equal in content).

o Print the results.

Page | 63
Source Code
// [Link]

class Student {

int id;

String name;

// a) Parameterized constructor

public Student(int id, String name) {

[Link] = id;

[Link] = name;

// b) Function to check if two objects are equal in content

public static boolean isEqual(Student s1, Student s2) {

if ([Link] == [Link] && [Link]([Link])) {

return true;

return false;

// Main class to test the functionality

public class TestStudentEquality {

public static void main(String[] args) {

// Create student objects

Student student1 = new Student(101, "Alice");

Student student2 = new Student(102, "Bob");

Student student3 = new Student(101, "Alice"); // A duplicate of


student1

// c) Print the result of the comparisons

Page | 64
[Link]("Are student1 and student2 equal? " +
[Link](student1, student2));

[Link]("Are student1 and student3 equal? " +


[Link](student1, student3));

Output
Are student1 and student2 equal? false

Are student1 and student3 equal? true

Discussion
This program successfully demonstrates how to implement a method for content-based object
comparison. The isEqual() method, implemented as a static function, clearly shows how to compare
the instance variables of two distinct objects. It's important to use [Link]() for comparing
strings, not ==, as == only checks for reference equality. This solution correctly identifies that
student1 and student3 are logically equal despite being separate objects in memory.

Page | 65
23. Abstract Class: Employee, Manager, and Clerk

Problem Statement
Create an abstract class Employee with properties and an abstract function for calculating net salary.
Also, include an abstract function for displaying information. Derive Manager and Clerk classes from
this abstract class and implement the abstract methods.

Theory
An abstract class is a class that cannot be instantiated on its own; it serves as a blueprint for its
subclasses. It can contain both concrete methods and abstract methods, which have no body and
must be implemented by any non-abstract subclass. This design pattern enforces a contract, ensuring
that all subclasses provide specific functionalities. In this problem, the Employee class defines the
common behavior, and the Manager and Clerk classes provide the specific implementations for
calculateNetSalary() and displayInfo(), showcasing polymorphism.

Algorithm
1. Abstract Employee Class:

o Variables: name, id, salary.

o Constructor: Initialize common properties.

o Abstract Methods: abstract double calculateNetSalary(), abstract void displayInfo().

2. Manager Class (inherits from Employee):

o Variables: bonus: double.

o Constructor: Call super() to initialize inherited properties and initialize bonus.

o Implement calculateNetSalary(): Return salary + bonus.

o Override displayInfo(): Print manager-specific details.

3. Clerk Class (inherits from Employee):

o Variables: otPay: double (overtime pay).

o Constructor: Call super() and initialize otPay.

o Implement calculateNetSalary(): Return salary + otPay.

o Override displayInfo(): Print clerk-specific details.

4. main Method:

o Create instances of Manager and Clerk.

o Call their methods to calculate and display information.

Source Code
// Abstract [Link]

abstract class Employee {

Page | 66
String name;

int id;

double salary;

public Employee(String name, int id, double salary) {

[Link] = name;

[Link] = id;

[Link] = salary;

// Abstract method to be implemented by subclasses

public abstract double calculateNetSalary();

// Abstract method to be implemented by subclasses

public abstract void displayInfo();

// [Link]

class Manager extends Employee {

double bonus;

public Manager(String name, int id, double salary, double bonus) {

super(name, id, salary);

[Link] = bonus;

@Override

public double calculateNetSalary() {

return salary + bonus;

Page | 67
@Override

public void displayInfo() {

[Link]("Type: Manager");

[Link]("Name: " + name);

[Link]("ID: " + id);

[Link]("Salary: $" + salary);

[Link]("Bonus: $" + bonus);

// [Link]

class Clerk extends Employee {

double otPay;

public Clerk(String name, int id, double salary, double otPay) {

super(name, id, salary);

[Link] = otPay;

@Override

public double calculateNetSalary() {

return salary + otPay;

@Override

public void displayInfo() {

[Link]("Type: Clerk");

[Link]("Name: " + name);

[Link]("ID: " + id);

Page | 68
[Link]("Salary: $" + salary);

[Link]("Overtime Pay: $" + otPay);

// Main class to test

public class TestEmployee {

public static void main(String[] args) {

// Create a Manager object

Employee manager = new Manager("Alice", 101, 75000, 10000);

[Link]();

[Link]("Net Salary: $" +


[Link]());

[Link]("--------------------");

// Create a Clerk object

Employee clerk = new Clerk("Bob", 102, 45000, 500);

[Link]();

[Link]("Net Salary: $" + [Link]());

Page | 69
Output
Type: Manager

Name: Alice

ID: 101

Salary: $75000.0

Bonus: $10000.0

Net Salary: $85000.0

--------------------

Type: Clerk

Name: Bob

ID: 102

Salary: $45000.0

Overtime Pay: $500.0

Net Salary: $45500.0

Discussion
This program is a great example of using an abstract class to define a common structure while
allowing subclasses to provide their own specific implementations. The Employee class forces the
subclasses to implement calculateNetSalary() and displayInfo(), ensuring consistency across all types
of employees. This is a core concept of polymorphism, as a single Employee reference can point to
either a Manager or a Clerk object, and the appropriate method implementation will be called at
runtime.

Page | 70

You might also like