Q1.
Write a program in java that sorts half of element in
ascending and rest half of the elements in descending
order.
Source Code:
import [Link].*;
class HalfSort
static void printOrder(int[] arr, int n)
// sorting the array
[Link](arr);
// printing first half in ascending
// order
for (int i = 0; i < n / 2; i++)
[Link](arr[i]+" ");
// printing second half in descending
// order
for (int j = n - 1; j >= n / 2; j--)
[Link](arr[j]+" ");
public static void main(String[] args)
int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, 7 };
int n = [Link];
printOrder(arr, n);
1
Output:
2
Q2. Write a program in java that accepts a 2D matrix and
prints the matrix with row minimum and column minimum
values.
Source Code:
import [Link].*;
class MatrixMin
static void printMin(int[][] matrix, int rows, int cols)
// Print row minimums
[Link]("Row Minimums:");
for (int i = 0; i < rows; i++)
// Initialize rowMin
int rowMin = matrix[i][0];
// Iterate through columns
for (int j = 1; j < cols; j++)
// Update rowMin if necessary
if (matrix[i][j] < rowMin)
rowMin = matrix[i][j];
[Link]("Row " + (i + 1) + ": " + rowMin + " ");
[Link](); // Newline for formatting
// Print column minimums
[Link]("Column Minimums:");
for (int j = 0; j < cols; j++)
// Initialize colMin
3
int colMin = matrix[0][j];
// Iterate through rows
for (int i = 1; i < rows; i++)
// Update colMin if necessary
if (matrix[i][j] < colMin)
colMin = matrix[i][j];
[Link]("Column " + (j + 1) + ": " + colMin + " ");
[Link](); // Newline for formatting
public static void main(String[] args)
int[][] matrix = {
{3, 1, 4},
{1, 5, 9},
{2, 6, 5}
};
int rows = [Link];
int cols = matrix[0].length;
printMin(matrix, rows, cols);
4
Output:
5
Q3. Write a program in java to delete all consonants from
an input string and print the result string.
Source Code:
import [Link].*;
class ConsonantDeletion
{
static void deleteConsonants(String str)
{
String result = "";
for (int i = 0; i < [Link](); i++)
{
char ch = [Link](i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch ==
'U')
{
result += ch;
}
}
[Link](result);
}
public static void main(String[] args)
{
// Use Scanner for user input
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link](); // Read the entire line of input
deleteConsonants(str);
[Link](); // Close the scanner to prevent resource leaks
(important!)
}
}
6
Output:
7
Q4. A class called MyPoint, which models a 2D point with x
and y coordinates. It contains:
• Two instance variables x (int) and y (int).
• A default (or "no-argument" or "no-arg") constructor that
construct a point at the default location of (0, 0).
• A overloaded constructor that constructs a point with the
given x and y coordinates.
• A method setXY() to set both x and y.
• A method getXY() which returns the x and y in a 2-
element int array.
• A toString() method that returns a string description of the
instance in the format "(x, y)".
• A method called distance(int x, int y) that returns the
distance from this point to another point at the given (x, y)
coordinates, Write the MyPoint class. Also write a test driver
(called TestMyPoint) to test all the public methods defined
in the class.
Source Code:
//For [Link]
import [Link].*;
class MyPoint {
int x;
int y;
MyPoint() {
// Default constructor
x = 0;
y = 0;
}
8
MyPoint(int x, int y) {
// Overloaded constructor
this.x = x;
this.y = y;
}
void setXY(int x, int y) {
this.x = x;
this.y = y;
}
int[] getXY() {
int[] xy = new int[2];
xy[0] = x;
xy[1] = y;
return xy;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}
}
//For [Link]
import [Link].*;
9
class TestMyPoint {
public static void main(String[] args) {
// Test default constructor
MyPoint p1 = new MyPoint();
[Link]("p1: " + p1); // Output: p1: (0, 0)
// Test overloaded constructor
MyPoint p2 = new MyPoint(3, 4);
[Link]("p2: " + p2); // Output: p2: (3, 4)
// Test setXY()
[Link](5, 6);
[Link]("p1 after setXY(): " + p1); // Output: p1
after setXY(): (5, 6)
// Test getXY()
int[] xy = [Link]();
[Link]("p2 x: " + xy[0] + ", y: " + xy[1]); //
Output: p2 x: 3, y: 4
// Test distance(int, int)
double dist = [Link](1, 2);
[Link]("Distance from p1 to (1, 2): " + dist); //
Output should be approximately 5
dist = [Link](0,0);
[Link]("Distance from p2 to (0,0): " + dist); //
Output should be 5
}
}
10
Output:
11
Q5. Create a superclass ‘Person’ and two subclasses
‘Student’ and ‘Staff’. The following are the instance
variables and methods:
a. For ‘Person’ instance variables: name:String,
address:String. Initiate variable through constructor,
incorporate one method setPerson() that updates Person
variables , another method tostring() that shows Person
details as “Person[name=?,address=?”.
b. For ‘Student’ sub class instance variables:
program:String, year:String, fees:double. Initiate both
‘Student’ and ‘Person’ variables through constructor,
incorporate one method setStudent() that updates both
student and ‘Person’ data, another method tostring() that
shows ‘Person-Student’ details as
“Person[name=?,address=?,Program=?,Year=?,Fees=?”.
c. For ‘Staff’ subclass instance variables: school:String,
pay:double. Initiate both ‘Staff’ and ‘Person’ variables
through constructor, incorporate one method setStaff() that
updates both ‘staff’ and ‘Person’ data, another method
tostring() that shows ‘Person-Staff’ details as
“Person[name=?,address=?,School=?,Pays=?”.
Write the classes and a test driver main class to test all
functions mentioned above.
Source Code:
import [Link].*;
class Person {
String name;
String address;
Person(String name, String address) {
[Link] = name;
[Link] = address;
12
}
void setPerson(String name, String address) {
[Link] = name;
[Link] = address;
}
public String toString() {
return "Person[name=" + name + ",address=" + address + "]";
}
}
class Student extends Person {
String program;
String year;
double fees;
Student(String name, String address, String program, String year,
double fees) {
super(name, address);
[Link] = program;
[Link] = year;
[Link] = fees;
}
void setStudent(String name, String address, String program, String
year, double fees) {
[Link](name, address);
[Link] = program;
[Link] = year;
[Link] = fees;
}
public String toString() {
13
return "Person[name=" + name + ",address=" + address +
",Program=" + program + ",Year=" + year + ",Fees=" + fees + "]";
}
}
class Staff extends Person {
String school;
double pay;
Staff(String name, String address, String school, double pay) {
super(name, address);
[Link] = school;
[Link] = pay;
}
void setStaff(String name, String address, String school, double pay)
{
[Link](name, address);
[Link] = school;
[Link] = pay;
}
public String toString() {
return "Person[name=" + name + ",address=" + address + ",School="
+ school + ",Pays=" + pay + "]";
}
}
public class TestPerson { // Main class must be public
public static void main(String[] args) {
Person p = new Person("Debmalya", "Uluberia");
[Link](p);
[Link]("Ayush", "Santragachi");
[Link](p);
14
Student s = new Student("Arnab Mukherjee", "Maurigram", "Computer
Science", "2024", 10000.0);
[Link](s);
[Link]("Neha", "Amta", "Electrical Engineering", "2025",
12000.0);
[Link](s);
Staff st = new Staff("Amitava", "Andul", "Engineering", 50000.0);
[Link](st);
[Link]("Rudrapratap", "Andul", "Science", 60000.0);
[Link](st);
}
}
Output:
15
Q6. Create a base class ‘Square’ having instance variable
side:double. Initiate variable using constructor, a method
‘getVolume() : double’ that calculates volume and print it.
Create a derived class ‘Cylinder’ having instance variable
height:double. Initiate variables of both classes through
constructor, override method ‘getVolume() : double’ to
calculate volume of cylinder taking ‘side’ variable of base
class as ‘radius’ and print it
Source Code:
import [Link].*;
class Square {
double side;
Square(double side) {
[Link] = side;
}
double getVolume() {
double volume = side * side * side;
[Link]("Volume of Square (Cube): " + volume);
return volume;
}
}
class Cylinder extends Square {
double height;
Cylinder(double side, double height) {
super(side);
[Link] = height;
}
@Override
16
double getVolume() {
double volume = [Link] * side * side * height;
[Link]("Volume of Cylinder: " + volume);
return volume;
}
}
public class TestShapes { // Main class must be public
public static void main(String[] args) {
Square sq = new Square(5.0);
[Link]();
Cylinder cy = new Cylinder(3.0, 7.0);
[Link]();
}
}
Output:
17
Q7. Consider you are designing vehicles engine with
‘speed:int, gear:int’. you can define your engine
functionalities ‘speedUp(value)’ and ‘changeGear(value) in
an interface. The class which is implementing the interface
should implement all the methods in the interface.
Source Code:
//Define the Engine interface
interface Engine {
void speedUp(int value);
void changeGear(int value);
}
// Implementing class for Engine interface
class CarEngine implements Engine {
private int speed;
private int gear;
// Constructor
public CarEngine() {
[Link] = 0;
[Link] = 1; // Default gear
}
// Implementing the speedUp method
@Override
public void speedUp(int value) {
speed += value;
[Link]("Speeding up. Current speed: " + speed + " km/h");
}
// Implementing the changeGear method
@Override
public void changeGear(int value) {
gear = value;
[Link]("Changing gear to: " + gear);
}
}
// Main class for testing
public class engineGear {
public static void main(String[] args) {
// Creating an instance of CarEngine
18
CarEngine carEngine = new CarEngine();
// Testing the functionalities
[Link](30);
[Link](2);
[Link](20);
}
}
Output:
19
Q8. Write a program in java that handles both
‘ArrayIndexOutOfBoundsException’ and
‘ArithmeticException’
Source Code:
public class ExceptionHandling
{
public static void main(String[] args)
{
int a = 5;
int b = 0;
int arr[] = {12, 6, 5, 89, 10, 61};
try
{
[Link](a / b);
}
catch (ArithmeticException e)
{
[Link]("ArithmeticException: " + e + "\n");
}
try
{
[Link](arr[6]);
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBoundsException: " + e);
}
}
}
Output:
20
Q9. Write a program to create your own exception as
NegativeSizeException whenever negative values are put in
an array.
Source Code:
import [Link];
public class arnab {
static class NegativeSizeException extends Exception {
public NegativeSizeException(String message) {
super(message);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int size = [Link]();
try {
if (size < 0) {
throw new NegativeSizeException("Array size cannot be
negative.");
}
int[] arr = new int[size];
[Link]("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
arr[i] = [Link]();
}
[Link]("Array elements:");
for (int i = 0; i < size; i++) {
[Link](arr[i] + " ");
}
} catch (NegativeSizeException e) {
[Link]("Error: " + [Link]());
}
}
}
Output:
21
22
Q10. Write a Java program to remove a specific element
from an array.
Source Code:
import [Link].*;
public class RemoveElementFromArray {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int size = [Link]();
int[] arr = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
arr[i] = [Link]();
}
[Link]("Enter the element to remove: ");
int elementToRemove = [Link]();
// Find the index of the element to be removed
int indexToRemove = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == elementToRemove) {
indexToRemove = i;
break;
}
}
if (indexToRemove == -1) {
[Link]("Element not found in the array.");
} else {
// Shift elements to the left after the removed element
for (int i = indexToRemove; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
// Create a new array with the correct size
int[] newArray = new int[size - 1];
// Copy elements to the new array
for (int i = 0; i < size - 1; i++) {
newArray[i] = arr[i];
}
[Link]("Array after removing " + elementToRemove + ": ");
for (int i = 0; i < size - 1; i++) {
[Link](newArray[i] + " ");
23
}
}
}
}
Output:
24
Q11. Write a Java program to insert an element (specific
position) into an array.
Source Code:
import [Link].*;
public class InsertElement {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int size = [Link]();
int[] arr = new int[size];
[Link]("Enter the array elements:");
for (int i = 0; i < size; i++) {
arr[i] = [Link]();
}
[Link]("Enter the element to insert: ");
int elementToInsert = [Link]();
[Link]("Enter the position to insert at (0-based
index): ");
int position = [Link]();
// Check if the position is valid
if (position < 0 || position > size) {
[Link]("Invalid position.");
return;
}
// Create a new array with one extra space
int[] newArray = new int[size + 1];
// Copy elements from the original array to the new array
for (int i = 0; i < position; i++) {
newArray[i] = arr[i];
}
// Insert the new element at the specified position
newArray[position] = elementToInsert;
// Copy the remaining elements from the original array to the new
array
for (int i = position; i < size; i++) {
newArray[i + 1] = arr[i];
}
[Link]("Array after insertion: ");
25
for (int i = 0; i < size + 1; i++) {
[Link](newArray[i] + " ");
}
[Link]();
}
}
Output:
26