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 java.util.*;
class HalfSort
static void printOrder(int[] arr, int n)
// sorting the array
Arrays.sort(arr);
// printing first half in ascending
// order
for (int i = 0; i < n / 2; i++)
System.out.print(arr[i]+" ");
// printing second half in descending
// order
for (int j = n - 1; j >= n / 2; j--)
System.out.print(arr[j]+" ");
public static void main(String[] args)
int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, 7 };
int n = arr.length;
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 java.util.*;
class MatrixMin
static void printMin(int[][] matrix, int rows, int cols)
// Print row minimums
System.out.println("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];
System.out.print("Row " + (i + 1) + ": " + rowMin + " ");
System.out.println(); // Newline for formatting
// Print column minimums
System.out.println("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];
System.out.print("Column " + (j + 1) + ": " + colMin + " ");
System.out.println(); // Newline for formatting
public static void main(String[] args)
int[][] matrix = {
{3, 1, 4},
{1, 5, 9},
{2, 6, 5}
};
int rows = matrix.length;
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 java.util.*;
class ConsonantDeletion
{
static void deleteConsonants(String str)
{
String result = "";
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch ==
'U')
{
result += ch;
}
}
System.out.println(result);
}
public static void main(String[] args)
{
// Use Scanner for user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine(); // Read the entire line of input
deleteConsonants(str);
scanner.close(); // 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 MyPoint.java
import java.util.*;
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 Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
//For MyTestPoint.java
import java.util.*;
9
class TestMyPoint {
public static void main(String[] args) {
// Test default constructor
MyPoint p1 = new MyPoint();
System.out.println("p1: " + p1); // Output: p1: (0, 0)
// Test overloaded constructor
MyPoint p2 = new MyPoint(3, 4);
System.out.println("p2: " + p2); // Output: p2: (3, 4)
// Test setXY()
p1.setXY(5, 6);
System.out.println("p1 after setXY(): " + p1); // Output: p1
after setXY(): (5, 6)
// Test getXY()
int[] xy = p2.getXY();
System.out.println("p2 x: " + xy[0] + ", y: " + xy[1]); //
Output: p2 x: 3, y: 4
// Test distance(int, int)
double dist = p1.distance(1, 2);
System.out.println("Distance from p1 to (1, 2): " + dist); //
Output should be approximately 5
dist = p2.distance(0,0);
System.out.println("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 java.util.*;
class Person {
String name;
String address;
Person(String name, String address) {
this.name = name;
this.address = address;
12
}
void setPerson(String name, String address) {
this.name = name;
this.address = 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);
this.program = program;
this.year = year;
this.fees = fees;
}
void setStudent(String name, String address, String program, String
year, double fees) {
super.setPerson(name, address);
this.program = program;
this.year = year;
this.fees = 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);
this.school = school;
this.pay = pay;
}
void setStaff(String name, String address, String school, double pay)
{
super.setPerson(name, address);
this.school = school;
this.pay = 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");
System.out.println(p);
p.setPerson("Ayush", "Santragachi");
System.out.println(p);
14
Student s = new Student("Arnab Mukherjee", "Maurigram", "Computer
Science", "2024", 10000.0);
System.out.println(s);
s.setStudent("Neha", "Amta", "Electrical Engineering", "2025",
12000.0);
System.out.println(s);
Staff st = new Staff("Amitava", "Andul", "Engineering", 50000.0);
System.out.println(st);
st.setStaff("Rudrapratap", "Andul", "Science", 60000.0);
System.out.println(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 java.util.*;
class Square {
double side;
Square(double side) {
this.side = side;
}
double getVolume() {
double volume = side * side * side;
System.out.println("Volume of Square (Cube): " + volume);
return volume;
}
}
class Cylinder extends Square {
double height;
Cylinder(double side, double height) {
super(side);
this.height = height;
}
@Override
16
double getVolume() {
double volume = Math.PI * side * side * height;
System.out.println("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);
sq.getVolume();
Cylinder cy = new Cylinder(3.0, 7.0);
cy.getVolume();
}
}
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() {
this.speed = 0;
this.gear = 1; // Default gear
}
// Implementing the speedUp method
@Override
public void speedUp(int value) {
speed += value;
System.out.println("Speeding up. Current speed: " + speed + " km/h");
}
// Implementing the changeGear method
@Override
public void changeGear(int value) {
gear = value;
System.out.println("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
carEngine.speedUp(30);
carEngine.changeGear(2);
carEngine.speedUp(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
{
System.out.println(a / b);
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException: " + e + "\n");
}
try
{
System.out.println(arr[6]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("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 java.util.Scanner;
public class arnab {
static class NegativeSizeException extends Exception {
public NegativeSizeException(String message) {
super(message);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
try {
if (size < 0) {
throw new NegativeSizeException("Array size cannot be
negative.");
}
int[] arr = new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Array elements:");
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
} catch (NegativeSizeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
21
22
Q10. Write a Java program to remove a specific element
from an array.
Source Code:
import java.util.*;
public class RemoveElementFromArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter the array elements:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the element to remove: ");
int elementToRemove = scanner.nextInt();
// 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) {
System.out.println("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];
}
System.out.print("Array after removing " + elementToRemove + ": ");
for (int i = 0; i < size - 1; i++) {
System.out.print(newArray[i] + " ");
23
}
}
}
}
Output:
24
Q11. Write a Java program to insert an element (specific
position) into an array.
Source Code:
import java.util.*;
public class InsertElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter the array elements:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the element to insert: ");
int elementToInsert = scanner.nextInt();
System.out.print("Enter the position to insert at (0-based
index): ");
int position = scanner.nextInt();
// Check if the position is valid
if (position < 0 || position > size) {
System.out.println("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];
}
System.out.print("Array after insertion: ");
25
for (int i = 0; i < size + 1; i++) {
System.out.print(newArray[i] + " ");
}
scanner.close();
}
}
Output:
26