Java Program to Sort Array Halves
Java Program to Sort Array Halves
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];
Page | 1
[Link]("Original array: " +
[Link](arr));
int n = [Link];
int mid = n / 2;
[Link](arr, 0, mid);
int end = n - 1;
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
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.
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 After checking all elements in the row, store minRow in the row minimums array and
print it.
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.
Source Code
import [Link];
int[][] matrix = {
Page | 4
{3, 5, 2},
{8, 4, 1},
{7, 6, 9}
};
[Link]("Original Matrix:");
[Link]([Link](matrix[i]));
[Link]();
[Link]("Row Minimums:");
minRow = matrix[i][j];
[Link]();
[Link]("Column Minimums:");
Page | 5
minCol = matrix[i][j];
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 {
String inputString = "The quick brown fox jumps over the lazy
dog.";
char ch = [Link](i);
if (isVowel(ch)) {
[Link](ch);
Page | 7
} else if () {
[Link](ch);
ch = [Link](ch);
Output
Original string: The quick brown fox jumps over the lazy dog.
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 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.
● 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:
4. setXY(int x, int y): A method that assigns the input x and y values to the instance variables.
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.
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]
private int x;
private int y;
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
// Overloaded constructor
this.x = x;
this.y = y;
// setXY() method
this.x = x;
this.y = y;
// getXY() method
result[0] = this.x;
Page | 10
result[1] = this.y;
return result;
// toString() method
@Override
// distance() method
// [Link]
// Test setXY()
[Link](1, 1);
Page | 11
// Test getXY()
Output
Default point: (0,0)
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:
Source Code
// [Link]
Page | 13
public class Person {
[Link] = name;
[Link] = address;
[Link] = name;
[Link] = address;
@Override
// [Link]
[Link] = program;
[Link] = year;
[Link] = fees;
[Link] = program;
[Link] = year;
Page | 14
[Link] = fees;
@Override
// [Link]
[Link] = school;
[Link] = pay;
public void setStaff(String name, String address, String school, double pay)//
cite: 30
[Link] = school;
[Link] = pay;
@Override
// [Link]
Page | 15
Person p1 = new Person("John Doe", "123 Main St");
[Link]("\n------------------------\n");
[Link]("\n------------------------\n");
Staff st1 = new Staff("Bob", "202 Birch Dr", "Tech High", 60000.0); //
cite: 30
Page | 16
Output
Initial Person: Person [name=John Doe, address=123 Main St]
------------------------
------------------------
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:
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:
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
Source Code
// [Link]
class Square {
[Link] = side;
Page | 18
// Method to calculate and print volume of a cube
// [Link]
[Link] = height;
@Override
Page | 19
Square myCube = new Square(5.0);
[Link]();
Output
Volume of the cube: 125.0
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.
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 {
Page | 21
@Override
[Link] += value;
@Override
[Link] = value;
[Link] = 0;
[Link] = 0;
[Link]("Initial State:");
[Link]("\nExecuting functionalities:");
[Link](20);
[Link](2);
[Link](30);
[Link](4);
Page | 22
Output
Initial State:
Speed: 0, Gear: 0
Executing functionalities:
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.
4. catch blocks: Follow the try block with two separate catch blocks.
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
[Link]("--- Demonstrating
ArrayIndexOutOfBoundsException ---");
try {
} catch (ArrayIndexOutOfBoundsException e) {
Page | 24
[Link]("Error: You are trying to access an array
index that does not exist.");
try {
int a = 10;
int b = 0;
} catch (ArithmeticException e) {
Output
--- Demonstrating ArrayIndexOutOfBoundsException ---
Error: You are trying to access an array index that does not exist.
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).
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 (?).
5. View Records:
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];
Page | 26
static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database_name";
try {
// [Link]("[Link]");
// Open a connection
[Link]("Name: ");
[Link]("City: ");
pstmt = [Link](sql);
[Link](1, regNo);
[Link](2, sName);
Page | 27
[Link](3, city);
[Link](4, contactNo);
stmt = [Link]();
ResultSet rs = [Link](selectSql);
[Link]("------------------------------------------
------------------------");
while ([Link]()) {
[Link]("Regno"),
[Link]("Sname"),
[Link]("City"),
[Link]("ContactNo"));
[Link]();
[Link]();
} finally {
try {
try {
Page | 28
if (stmt != null) [Link]();
try {
[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
Name: Alice
------------------------------------------------------------------
...
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.
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];
if (originalArray[i] == elementToRemove) {
indexToRemove = i;
break;
Page | 31
// Check if the element was found
if (indexToRemove == -1) {
return;
// Create a new array with a size one less than the original
if (i != indexToRemove) {
newArray[j++] = originalArray[i];
Output
Original Array: [10, 20, 30, 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 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];
Page | 33
for (int i = 0; i < positionToInsert; i++) {
newArray[i] = originalArray[i];
newArray[positionToInsert] = elementToInsert;
newArray[i + 1] = originalArray[i];
Output
Original Array: [10, 20, 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
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.
Source Code
import [Link];
// Input size
int n = [Link]();
// Input elements
Page | 35
[Link]("Enter elements:");
arr[i] = [Link]();
// Find pairs
found = true;
if (!found) {
Page | 36
Sample Input
Enter size of array: 6
Enter elements:
2 4 3 5 7 8
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 Space = O(1).
● Optimized Approach:
● Edge cases:
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:
2. Traverse the array and copy only unique elements to a new array.
Algorithm
1. Input array size and elements.
Source Code
import [Link];
import [Link];
// Input size
Page | 38
int n = [Link]();
// Input elements
[Link]("Enter elements:");
arr[i] = [Link]();
[Link](arr);
// Remove duplicates
int j = 0;
temp[j++] = arr[i];
// Print result
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
Discussion
● Sorting ensures duplicates are adjacent.
● Complexity:
o Traversal → O(n)
● Alternative: Use HashSet (simpler, O(n)) but output order is not guaranteed.
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.
Approaches:
o For each number, check if it is the start of a sequence (num-1 not in set).
Algorithm
1. Input array elements.
Source Code
import [Link];
Page | 41
import [Link];
// Input size
int n = [Link]();
// Input elements
[Link]("Enter elements:");
arr[i] = [Link]();
[Link](num);
int longest = 0;
int length = 1;
currentNum++;
Page | 42
length++;
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 Overall → O(n).
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:
▪ Returns 0 if equal.
Example:
● "hello".compareTo("hello") → 0.
Algorithm
1. Read two strings.
Source Code
import [Link];
Page | 44
[Link]("Enter second string: ");
// Compare lexicographically
if (result == 0) {
} else {
Sample Input
Enter first string: apple
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).
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 :
Theory
● Java provides the method regionMatches() in the String class.
● Syntax:
● Parameters:
Example:
String s1 = "HelloWorld";
String s2 = "SayHelloWorldNow";
Algorithm
1. Read two strings from user.
4. Print result.
Page | 46
Source Code
import [Link];
// Input strings
// Compare regions
Page | 47
Sample Input
Enter first string: HelloWorld
Sample Output
str1[0 - 4] == str2[3 - 7]? true
Discussion
● Uses regionMatches() to check substring equality without extracting substrings.
Page | 48
Problem Statement 17
Write a Java program to print all permutations of a given string with repetition.
Example:
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
Example:
For string "PQR" (n = 3), length = 3 →
Total permutations = 33=273^3 = 2733=27.
Algorithm
1. Input the string.
o Recursive case → for each character, append it and recurse for remaining length.
Source Code
import [Link];
// Recursive function
if (length == 0) {
[Link](prefix);
Page | 49
return;
// Input string
Page | 50
Sample Input
Enter a string: PQR
PPP
PPQ
PPR
PQP
PQQ
PQR
PRP
PRQ
PRR
QPP
QPQ
...
Discussion
● This program uses recursion to generate permutations.
● Complexity:
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.
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.
Source Code
import [Link];
if ([Link]().isEmpty()) {
Page | 52
[Link]();
return;
[Link]();
Output
Input the string:
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 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 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
[Link] = length;
[Link] = breadth;
[Link] = height;
// Copy constructor
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
Page | 55
[Link]("Volume of myBox1: " + [Link]());
Output
Volume of myBox1: 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 Copy Constructor: Take an Employee object as an argument and copy its salary to
the new object.
o calculate() Method:
2. main Method:
o Call the calculate() method on this object to get the calculated values.
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
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
return this;
@Override
Page | 58
public static void main(String[] args) {
[Link] = 50000.0;
Output
Employee 1 (before calculation): Employee [salary=50000.0, pf=0.0,
allowances=0.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 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 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];
Page | 60
public NegativeSizeException(String message) {
super(message);
try {
if (size < 0) {
} catch (NegativeSizeException e) {
} finally {
[Link]();
Page | 61
Output
Enter the size of the array: -5
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 isEqual() Method:
▪ This method should be static, as it operates on two objects passed to it, not on
a single instance.
▪ It should return true if both objects have the same id and name, and false
otherwise.
2. main Method:
o Create a third Student object that is a duplicate of one of the first two.
▪ The first object and its duplicate (which should be equal in content).
Page | 63
Source Code
// [Link]
class Student {
int id;
String name;
// a) Parameterized constructor
[Link] = id;
[Link] = name;
return true;
return false;
Page | 64
[Link]("Are student1 and student2 equal? " +
[Link](student1, student2));
Output
Are student1 and student2 equal? false
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:
4. main Method:
Source Code
// Abstract [Link]
Page | 66
String name;
int id;
double salary;
[Link] = name;
[Link] = id;
[Link] = salary;
// [Link]
double bonus;
[Link] = bonus;
@Override
Page | 67
@Override
[Link]("Type: Manager");
// [Link]
double otPay;
[Link] = otPay;
@Override
@Override
[Link]("Type: Clerk");
Page | 68
[Link]("Salary: $" + salary);
[Link]();
[Link]("--------------------");
[Link]();
Page | 69
Output
Type: Manager
Name: Alice
ID: 101
Salary: $75000.0
Bonus: $10000.0
--------------------
Type: Clerk
Name: Bob
ID: 102
Salary: $45000.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