Data Structures
1. Implement a function that receives an array of integers and returns the first repeating
element. If there are no repeating elements, return -1.
Input Format
The input begins with an integer N (the size of the array), followed by N space-
separated integers (the elements of the array).
Output Format
Output the first repeating element.
Output -1 if no such element exists.
If the input is non-integer print Invalid input.
Solution
import [Link].*;
public class FirstRepeatingElement {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
int n = [Link]([Link]());
if (n < 1 || n > 1000) {
[Link]("Invalid input");
return;
int[] arr = new int[n];
Set<Integer> seen = new HashSet<>();
Set<Integer> repeated = new HashSet<>();
for (int i = 0; i < n; i++) {
if (![Link]()) {
[Link]("Invalid input");
return;
arr[i] = [Link]();
if ([Link](arr[i])) {
[Link](arr[i]);
} else {
[Link](arr[i]);
for (int i = 0; i < n; i++) {
if ([Link](arr[i])) {
[Link](arr[i]);
return;
[Link]("-1");
} catch (Exception e) {
[Link]("Invalid input");
} finally {
[Link]();
Sample Input
5
12325
Output
2. Given an integer array, implement a function that moves all zeroes in the array to the end
while maintaining the relative order of the non-zero elements. The function should modify
the array in place.
Input Format
An integer n represents the number of elements in the array.
An array arr of length n containing integer values representing the elements of the
array.
Output Format
Print the modified array with all zeroes moved to the end.
Solution
import [Link].*;
public class MoveZeroesToEnd {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
moveZeroesToEnd(arr);
for (int num : arr) {
[Link](num + " ");
[Link]();
[Link]();
}
public static void moveZeroesToEnd(int[] arr) {
int index = 0;
for (int i = 0; i < [Link]; i++) {
if (arr[i] != 0) {
int temp = arr[index];
arr[index++] = arr[i];
arr[i] = temp;
Sample Input
0 1 0 3 12 0
Output
1 3 12 0 0 0
3. Given an array, return the duplicates present in the array.
Input Format
An integer n represents the number of elements in the array.
A list of n integers, indicating the elements of the array.
Output Format
If duplicates are found, print each duplicate on a new line in the order they appear.
If no duplicates are found, print No duplicates found.
Solution
import [Link];
public class FindAllDuplicates {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// [Link]("Enter the number of elements: ");
int n = [Link]();
if (n <= 0) {
[Link]("Invalid input");
return;
int[] array = new int[n];
// [Link]("Enter the elements (positive integers only):");
for (int i = 0; i < n; i++) {
int value = [Link]();
if (value < 0) {
[Link]("Invalid input");
return;
array[i] = value;
// [Link]("Duplicates:");
findDuplicates(array);
[Link]();
private static void findDuplicates(int[] array) {
boolean hasDuplicates = false;
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (array[i] == array[j]) {
[Link](array[i]);
hasDuplicates = true;
break;
if (!hasDuplicates) {
[Link]("No duplicates found");
Input Format
352375
Output Format
4. Given an array of integers, implement a function that doubles the values at all odd indices
while keeping the values at even indices unchanged.
Input Format
The first line of input contains an integer n representing the number of elements in
the array.
The second line of input contains n integers representing the elements of the array.
Output Format
Print the array after doubling the values of elements at odd indices.
Solution
import [Link];
public class DoubleOddIndices {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
doubleOddIndices(arr);
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
[Link]();
[Link]();
public static void doubleOddIndices(int[] arr) {
for (int i = 1; i < [Link]; i += 2) {
arr[i] *= 2;
Sample Input
12345
Output
14385
5. Given a matrix of size m × n, implement a function that reads the matrix elements from
the user and prints its transpose.
Input Format
An integer m number of rows.
An integer n number of columns.
m×n integers representing the matrix values.
Output Format
Print the transposed matrix with values.
If the input is invalid (e.g., not integers or dimensions out of bounds), print Invalid
input.
Solution
import [Link];
class Matrix {
private int[][] matrix;
private int m, n;
public Matrix(int m, int n) {
this.m = m;
this.n = n;
matrix = new int[m][n];
public void setValues(Scanner scanner) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ([Link]()) {
matrix[i][j] = [Link]();
} else {
[Link]("Invalid input");
[Link](0); // Terminate the program on invalid input
}
}
public String getTranspose() {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
[Link](matrix[i][j]);
if (i < m - 1) [Link](" "); // Append space between elements in a row
if (j < n - 1) [Link]("\n"); // Append newline after each row except the last one
return [Link]();
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Validate that the input is an integer and within the correct range
if ([Link]()) {
int m = [Link]();
if ([Link]()) {
int n = [Link]();
// Validate that m and n are within the valid range (1 to 100)
if (m >= 1 && m <= 100 && n >= 1 && n <= 100) {
Matrix matrix = new Matrix(m, n);
[Link](scanner);
[Link]([Link]());
} else {
[Link]("Invalid input");
} else {
[Link]("Invalid input");
} else {
[Link]("Invalid input");
[Link]();
Sample Input
23
123
456
Output
14
25
36
6. Given a singly linked list of n integers, implement a function that sorts the linked list using
the insertion sort algorithm.
Input Format
The first line contains an integer n, the number of elements in the linked list.
The second line contains n integers, representing the elements of the linked list.
Output Format
Print the elements of the sorted linked list as space-separated integers.
Solution
import [Link];
class ListNode {
int val;
ListNode next;
ListNode(int val) {
[Link] = val;
[Link] = null;
public class InsertionSortLinkedList {
public static ListNode insertionSortList(ListNode head) {
if (head == null) return null;
ListNode sorted = null;
while (head != null) {
ListNode current = head;
head = [Link];
if (sorted == null || [Link] >= [Link]) {
[Link] = sorted;
sorted = current;
} else {
ListNode temp = sorted;
while ([Link] != null && [Link] < [Link]) {
temp = [Link];
[Link] = [Link];
[Link] = current;
}
return sorted;
public static void printList(ListNode head) {
while (head != null) {
[Link]([Link] + " ");
head = [Link];
[Link]();
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// [Link]("Enter the number of elements in the linked list: ");
int n = [Link]();
if (n < 0) {
[Link]("Invalid input");
return;
ListNode head = null;
ListNode tail = null;
// [Link]("Enter the elements of the linked list: ");
for (int i = 0; i < n; i++) {
int value = [Link]();
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
[Link] = newNode;
tail = newNode;
head = insertionSortList(head);
printList(head);
[Link]();
Sample Input
40 20 10 30 50
Output
10 20 30 40 50
7. You are given a singly linked list and an integer k. Your task is to reverse every k
consecutive nodes in the linked list. If there are fewer than k nodes left at the end of the list,
leave them as they are. The process should continue throughout the entire list, and the
modified list should be printed.
Input Format
A list of integers represents the value of the nodes.
Second line contains an integer k.
Output Format
Print the modified list after reversing every k nodes.
Solution
import [Link];
public class ReverseKGroup {
// Definition for singly-linked list.
static class ListNode {
int val;
ListNode next;
ListNode(int val) { [Link] = val; }
// Function to reverse k nodes in the linked list
public static ListNode reverseKGroup(ListNode head, int k) {
if (k <= 0) return head;
ListNode dummy = new ListNode(0);
[Link] = head;
ListNode prevGroupEnd = dummy;
ListNode current = head;
while (current != null) {
ListNode groupStart = current;
ListNode groupEnd = current;
// Check if there are k nodes left in the list
for (int i = 1; i < k; i++) {
groupEnd = [Link];
if (groupEnd == null) return [Link];
ListNode nextGroupStart = [Link];
ListNode prev = null;
ListNode curr = groupStart;
// Reverse k nodes
while (curr != nextGroupStart) {
ListNode next = [Link];
[Link] = prev;
prev = curr;
curr = next;
// Connect reversed group with previous and next groups
[Link] = prev;
[Link] = nextGroupStart;
prevGroupEnd = groupStart;
current = nextGroupStart;
return [Link];
// Function to print the linked list
public static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
[Link]([Link] + " ");
current = [Link];
[Link]();
// Function to create a linked list from user input
public static ListNode createListFromInput(String input) {
String[] parts = [Link]().split("\\s+");
if ([Link] == 0) return null;
ListNode head = new ListNode([Link](parts[0]));
ListNode current = head;
for (int i = 1; i < [Link]; i++) {
try {
ListNode newNode = new ListNode([Link](parts[i]));
[Link] = newNode;
current = newNode;
} catch (NumberFormatException e) {
[Link]("Invalid input");
return null;
return head;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// [Link]("Enter the linked list elements separated by spaces:");
String listInput = [Link]();
// [Link]("Enter the integer k:");
int k;
try {
k = [Link]([Link]().trim());
} catch (NumberFormatException e) {
[Link]("Invalid input");
return;
}
// Create the linked list from the input
ListNode head = createListFromInput(listInput);
if (head == null) return;
// Reverse the nodes in k groups
ListNode newHead = reverseKGroup(head, k);
// Print the modified linked list
// [Link]("Modified linked list:");
printList(newHead);
[Link]();
Sample Input
123456789
Output
432187659
8. Given an n × n square matrix, implement a function to rotate the matrix 90 degrees
clockwise.
Input Format
The first line contains an integer n representing the size of the matrix.
The next n lines each contain n integers, representing the elements of each row in
the matrix.
Output Format
Print the matrix after rotating it by 90 degrees clockwise. Each row of the rotated
matrix should be printed on a new line.
Solution
import [Link];
public class MatrixRotation {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
if (n < 1 || n > 500) {
[Link]("Invalid input");
return;
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ([Link]()) {
matrix[i][j] = [Link]();
} else {
[Link]("Invalid input");
return;
// Rotate the matrix by 90 degrees clockwise
rotateMatrix(matrix, n);
// Print the rotated matrix
printMatrix(matrix, n);
private static void rotateMatrix(int[][] matrix, int n) {
// Transpose the matrix
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
// Reverse each row
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
private static void printMatrix(int[][] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](matrix[i][j] + " ");
[Link]();
Sample Input
54
15
Output
15
54
9. Given an integer n representing the number of nodes in a binary tree, followed by n
integers representing the node values in level-order insertion, implement a function to
construct the binary tree and determine its height.
Input Format
The first line contains an integer n, the number of nodes in the binary tree.
The next n lines contain integers representing the keys of the nodes, inserted level-
wise (starting from the root).
Output Format
Print the height of the binary tree.
Solution
import [Link];
import [Link];
import [Link];
class BinaryTree {
static class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
Node root;
// Insert nodes level-wise
public void insertLevelOrder(int[] keys) {
Queue<Node> queue = new LinkedList<>();
root = new Node(keys[0]);
[Link](root);
int i = 1;
while (![Link]() && i < [Link]) {
Node current = [Link]();
if (i < [Link]) {
[Link] = new Node(keys[i++]);
[Link]([Link]);
if (i < [Link]) {
[Link] = new Node(keys[i++]);
[Link]([Link]);
// Calculate the height of the binary tree
public int calculateHeight(Node root) {
if (root == null) return -1; // Height of an empty tree is -1
int leftHeight = calculateHeight([Link]);
int rightHeight = calculateHeight([Link]);
return 1 + [Link](leftHeight, rightHeight);
// Handle invalid input
public static boolean validateInput(int n, int[] keys) {
if (n < 0 || n > 10) {
return false;
for (int key : keys) {
if (key < -100 || key > 100) {
return false;
return true;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
[Link](); // Consume newline
int[] keys = new int[n];
for (int i = 0; i < n; i++) {
try {
keys[i] = [Link]([Link]());
} catch (NumberFormatException e) {
[Link]("Invalid input");
return;
if () {
[Link]("Invalid input");
return;
BinaryTree tree = new BinaryTree();
if (n > 0) {
[Link](keys);
[Link]([Link]([Link]));
} else {
[Link](-1); // Empty tree height
[Link]();
Sample Input
10
20
30
Output
10. Given an integer n representing the number of nodes in a binary search tree (BST),
followed by n integers representing the node values in level-order insertion, and an
additional integer searchKey, implement a function to construct the BST and determine
whether the searchKey exists in the tree.
Input Format
The first line contains an integer n, the number of nodes in the binary search tree.
The next n lines contain integers representing the keys of the nodes, inserted level-
wise.
The last line contains the integer value to search in the BST.
Output Format
Print Found if the value exists in the tree, otherwise print Not Found.
Sample Input
10
15
Output
Found
11. Given a 4 × 4 adjacency matrix representing a directed graph, implement a function to
detect if the graph contains a cycle using Depth First Search (DFS) with recursion.
Input Format
The input starts with a V×V matrix, where V=4. Each of the next 4 lines contains 4
integers representing the adjacency matrix of the graph. All integers will be either 0
or 1.
Output Format
Print Graph contains cycle if the graph contains a cycle.
Print Graph doesn't contain cycle if no cycle exists.
Solution
import [Link];
public class GraphCycleDetection {
static final int V = 4;
static boolean isCyclicUtil(int v, boolean[] visited, boolean[] recStack, int[][] graph) {
if (!visited[v]) {
visited[v] = true;
recStack[v] = true;
for (int i = 0; i < V; i++) {
if (graph[v][i] != 0) { // If there's an edge
if (!visited[i] && isCyclicUtil(i, visited, recStack, graph))
return true;
else if (recStack[i])
return true;
recStack[v] = false; // Remove the vertex from recursion stack
return false;
static boolean isCyclic(int[][] graph) {
boolean[] visited = new boolean[V];
boolean[] recStack = new boolean[V];
// Check all vertices for cycle detection
for (int i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack, graph))
return true;
return false;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int[][] graph = new int[V][V];
boolean isValidInput = true;
// [Link]("Enter the adjacency matrix values (0 or 1):");
for (int i = 0; i < V; i++) {
// [Link]("Enter values for row " + (i + 1) + ": ");
for (int j = 0; j < V; j++) {
if ([Link]()) {
int input = [Link]();
// Check if input is 0 or 1
if (input != 0 && input != 1) {
[Link]("Invalid input");
isValidInput = false;
break;
graph[i][j] = input;
} else {
[Link]("Invalid input");
isValidInput = false;
break;
if (!isValidInput) break;
// If the input is valid, check for a cycle
if (isValidInput) {
if (isCyclic(graph)) {
[Link]("Graph contains cycle");
} else {
[Link]("Graph doesn't contain cycle");
[Link]();
}
Sample Input
0100
0010
0001
1000
Output
Graph contains cycle
12. Given an array of integers height representing the heights of vertical lines on a 2D plane,
where each line's width is 1, find the maximum area of water that can be trapped between
any two lines. The area is determined by the width of the container and the height of the
shorter line.
Input Format
An integer n, is the number of elements in the array height.
An array of n integers, where each height[i] represents the height of a vertical line.
Output Format
A single integer represents the maximum area of water that can be trapped between
two lines.
Solution
import [Link];
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = [Link] - 1;
int res = 0;
while (left < right) {
int containerLength = right - left;
int area = containerLength * [Link](height[left], height[right]);
res = [Link](res, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
return res;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = -1;
boolean invalidInput = false;
while (n <= 0) {
if (invalidInput) {
[Link]("Invalid input");
invalidInput = false;
// [Link]("Enter the number of elements (positive integer): ");
if ([Link]()) {
n = [Link]();
if (n <= 0) {
invalidInput = true;
n = -1;
} else {
invalidInput = true;
[Link]();
}
int[] height = new int[n];
int i = 0;
invalidInput = false;
while (i < n) {
if (invalidInput) {
[Link]("Invalid input");
invalidInput = false;
// [Link]("Enter element " + (i + 1) + ": ");
if ([Link]()) {
height[i] = [Link]();
i++;
} else {
invalidInput = true;
[Link]();
Solution solution = new Solution();
int result = [Link](height);
[Link](result);
[Link]();
Sample Input
71239456
Output
42
Database Management System
13. In a content management system (CMS), users are assigned different roles based on their
access level. The system has three types of roles: Administrator, Editor, and Viewer. Each
user is linked to a specific role, which defines their permissions in the system. Your task to
retrieve the names of all users along with their role descriptions. Use an INNER JOIN to
combine data from the users and roles tables.
Input Table
Users Table
Solution
CREATE TABLE roles (
role_id INT NOT NULL PRIMARY KEY,
role_description VARCHAR(100) NOT NULL
);
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY,
user_name VARCHAR(100) NOT NULL,
role_id INT NOT NULL,
FOREIGN KEY (role_id) REFERENCES roles(role_id)
);
INSERT INTO roles (role_id, role_description)
VALUES
(1, 'Administrator'),
(2, 'Editor'),
(3, 'Viewer');
INSERT INTO users (user_id, user_name, role_id)
VALUES
(101, 'Alice', 1),
(102, 'Bob', 2),
(103, 'Charlie', 3);
SELECT
u.user_name,
r.role_description
FROM
users u
INNER JOIN
roles r
ON
u.role_id = r.role_id;
Output Table
user_name | role_description
--------- | ----------------
Alice | Administrator
Bob | Editor
Charlie | Viewer
14. Emma is a Human Resources (HR) manager at a company. She wants to maintain a record
of all employees in a table called Employees. She needs to add a new employee, John Doe,
who has just joined the HR department.
The Employees table has the following columns:
ID (Unique Employee ID)
Name (Employee's Full Name)
Age (Employee's Age)
Department (Department Name)
Implement an SQL query to insert John Doe’s details (ID = 101, Name = 'John Doe', Age = 30,
Department = 'HR')
Solution
-- Create the Employees table
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Department VARCHAR(50)
);
-- Insert a new employee
INSERT INTO Employees (ID, Name, Age, Department)
VALUES (101, 'John Doe', 30, 'HR');
Select * from Employees;
Output Table
ID | Name | Age | Department
--- | -------- | --- | ----------
101 | John Doe | 30 | HR
15. Implement a SQL query to retrieve a list of all employees along with their department
[Link] have two tables:
Employees with columns: EmployeeID, EmployeeName, DepartmentID.
Departments with columns: DepartmentID, DepartmentName.
Solution
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(100),
DepartmentID INT
);
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(100)
);
INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID)
VALUES
(1, 'John Doe', 101),
(2, 'Jane Smith', 102),
(3, 'Alice Johnson', 103);
INSERT INTO Departments (DepartmentID, DepartmentName)
VALUES
(101, 'Sales'),
(102, 'Marketing'),
(103, 'Engineering');
SELECT [Link], [Link], [Link]
FROM Employees E
JOIN Departments D ON [Link] = [Link];
Output
EmployeeID | EmployeeName | DepartmentName
---------- | ------------- | --------------
1 | John Doe | Sales
2 | Jane Smith | Marketing
3 | Alice Johnson | Engineering
OOPS
16. A job recruitment portal allows companies to post job openings for full-time jobs and
internships. You need to implement a Job class with attributes jobTitle and companyName.
This class should be extended into:
FullTimeJob (inherits Job)
Internship (inherits Job and includes an additional attribute, stipend)
Each class should include a method to display job details appropriately.
Input Format
An integer N representing the number of job postings.
The next N lines contain:
Job Type (either "FullTime" or "Internship").
o A string jobTitle
o A string companyName
o If the job is an Internship, a floating-point stipend
Output Format
If the input is valid, print:
o For Full-Time Job: Full-Time Job: <jobTitle> at <companyName>
o For Internship: Internship: <jobTitle> at <companyName> with Stipend
<stipend>
Solution
import [Link].*;
class Job {
protected String jobTitle;
protected String companyName;
public Job(String jobTitle, String companyName) {
[Link] = jobTitle;
[Link] = companyName;
public void display() {
[Link]("Job: " + jobTitle + " at " + companyName);
class FullTimeJob extends Job {
public FullTimeJob(String jobTitle, String companyName) {
super(jobTitle, companyName);
@Override
public void display() {
[Link]("Full-Time Job: " + jobTitle + " at " + companyName);
}
class Internship extends Job {
private double stipend;
public Internship(String jobTitle, String companyName, double stipend) {
super(jobTitle, companyName);
[Link] = stipend;
@Override
public void display() {
[Link]("Internship: " + jobTitle + " at " + companyName + " with Stipend " +
stipend);
public class JobRecruitmentPortal {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int N = [Link]([Link]().trim());
for (int i = 0; i < N; i++) {
String[] input = [Link]().split(" ");
if ([Link] < 3) {
[Link]("Invalid input");
continue;
String jobType = input[0];
String jobTitle = input[1];
String companyName = input[2];
// Validate jobTitle and companyName length
if ([Link]() < 1 || [Link]() > 50 || [Link]() < 1 ||
[Link]() > 50) {
[Link]("Invalid");
continue;
if ([Link]("FullTime")) {
FullTimeJob job = new FullTimeJob(jobTitle, companyName);
[Link]();
} else if ([Link]("Internship")) {
if ([Link] != 4) {
[Link]("Invalid input");
continue;
try {
double stipend = [Link](input[3]);
if (stipend < 1000 || stipend > 50000) {
[Link]("Invalid input");
continue;
Internship internship = new Internship(jobTitle, companyName, stipend);
[Link]();
} catch (NumberFormatException e) {
[Link]("Invalid input");
} else {
[Link]("Invalid input");
[Link]();
}
}
Sample Input
FullTime Developer Google
Output
Full-Time Job: Developer at Google
17. You are working on a vehicle tracking system, implementing a base class Vehicle with
attributes and methods for general vehicle information. Create a subclass ElectricVehicle
that extends Vehicle and includes additional attributes and methods specific to electric
vehicles.
Input Format
1. For Vehicle
A single line with the make and model: make model
2. For ElectricVehicle
A single line with the make, model, battery capacity (in kWh), and charging status: make
model battery_capacity charging_status (True or False)
Output Format
Display the vehicle make and model.
Solution
import [Link];
class Vehicle {
private String make;
private String model;
public Vehicle(String make, String model) {
if ([Link]() || [Link]()) {
throw new IllegalArgumentException("Make and model must be non-empty.");
}
[Link] = make;
[Link] = model;
public void displayInfo() {
[Link]("" + make);
[Link]("" + model);
class ElectricVehicle extends Vehicle {
private double batteryCapacity; // in kWh
private boolean chargingStatus; // true if charging, false if not
public ElectricVehicle(String make, String model, double batteryCapacity, boolean
chargingStatus) {
super(make, model);
if (batteryCapacity <= 0) {
throw new IllegalArgumentException("Battery capacity must be a positive number.");
[Link] = batteryCapacity;
[Link] = chargingStatus;
@Override
public void displayInfo() {
[Link]();
[Link]("" + batteryCapacity + " kWh");
[Link]("" + (chargingStatus ? "Charging" : "Not Charging"));
}
public class VehicleTrackingSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// [Link]("Enter vehicle make and model:");
String vehicleInput = [Link]();
String[] vehicleData = [Link](" ");
Vehicle vehicle = new Vehicle(vehicleData[0], vehicleData[1]);
[Link]();
// [Link]("\nEnter electric vehicle make, model, battery capacity, and
charging status:");
String electricVehicleInput = [Link]();
String[] electricVehicleData = [Link](" ");
String make = electricVehicleData[0];
String model = electricVehicleData[1];
double batteryCapacity = [Link](electricVehicleData[2]);
boolean chargingStatus = [Link](electricVehicleData[3]);
ElectricVehicle electricVehicle = new ElectricVehicle(make, model, batteryCapacity,
chargingStatus);
[Link]();
[Link]();
Sample Input
Toyota Camry
Tesla ModelS 75 true
Output
Toyota
Camry
Tesla
ModelS
75.0 kWh
Charging
18. You are given the dimensions of a rectangle, specifically its length and width. Your task is
to calculate and print the area and perimeter of the rectangle.
Input Format
The first line of input contains a single floating-point number length, representing the
length of the rectangle.
The second line of input contains a single floating-point number width, representing
the width of the rectangle.
Output Format
Print the area of the rectangle on the first line and the perimeter of the rectangle on
the second line single floating-point number.
Code
import [Link];
class Rectangle {
public double length;
public double width;
public double calculateArea() {
return length * width;
public double calculatePerimeter() {
return 2 * (length + width);
public void displayResults() {
[Link](calculateArea());
[Link](calculatePerimeter());
}
public class RectangleMain {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Rectangle rectangle = new Rectangle();
// [Link]("Enter the length of the rectangle: ");
[Link] = [Link]();
// [Link]("Enter the width of the rectangle: ");
[Link] = [Link]();
if ([Link] <= 0 || [Link] <= 0) {
[Link]("Invalid input");
} else {
[Link]();
Sample Input
5.5
3.0
Output
16.5
17.0
19. You are given the lengths of three sides of a triangle. Create a class Triangle to determine
if these sides form a valid triangle(based on triangular inequality: a + b > c) and, if so, classify
the type of triangle they form. A triangle can be classified as:
Equilateral: All three sides are equal.
Isosceles: Exactly two sides are equal.
Scalene: All three sides are different.
Input Format
Three floating-point numbers representing the lengths of the sides of the triangle
(side1, side2, side3).
Output Format
If the input values form a valid triangle, the program should print the type of triangle
equilateral, isosceles, or scalene.
Code
import [Link];
class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double s1, double s2, double s3) {
side1 = s1;
side2 = s2;
side3 = s3;
public boolean isEquilateral() {
return (side1 == side2 && side2 == side3);
public boolean isIsosceles() {
return (side1 == side2 || side1 == side3 || side2 == side3);
public boolean isScalene() {
return (!isEquilateral() && !isIsosceles());
public boolean isValidTriangle() {
return (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1);
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
double s1 = [Link]();
double s2 = [Link]();
double s3 = [Link]();
Triangle triangle = new Triangle(s1, s2, s3);
if ([Link]()) {
if ([Link]()) {
[Link]("equilateral");
} else if ([Link]()) {
[Link]("isosceles");
} else if ([Link]()) {
[Link]("scalene");
} else {
[Link]("Invalid triangle");
[Link]();
Sample Input
3.0 3.0 3.0
Output
Equilateral
20. Dharani is planning to apply for a loan. She can choose between a home loan and a
personal loan. Each loan type has a specific interest rate of 5% for a home loan and 10% for
a personal loan. Samantha wants to enter the loan amount and type and get an instant
interest calculation. Implement an abstract class to help Dharani calculate the loan interest
amount based on her input.
Input Format
A double value for loanAmount represents the loan amount Dharani wants.
A string value for loanType represents the type of loan Dharani chooses.
Output Format
Print the interest for the specified loan.
Code
import [Link];
abstract class Loan {
protected double loanAmount;
public Loan(double loanAmount) {
[Link] = loanAmount;
public abstract double calculateInterest();
public void displayLoanDetails() {
[Link]( calculateInterest());
class HomeLoan extends Loan {
private static final double INTEREST_RATE = 0.05;
public HomeLoan(double loanAmount) {
super(loanAmount);
@Override
public double calculateInterest() {
return loanAmount * INTEREST_RATE;
}
class PersonalLoan extends Loan {
private static final double INTEREST_RATE = 0.10;
public PersonalLoan(double loanAmount) {
super(loanAmount);
@Override
public double calculateInterest() {
return loanAmount * INTEREST_RATE;
public class LoanCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
double loanAmount = [Link]();
if (loanAmount <= 0) throw new IllegalArgumentException("Invalid Input");
String loanType = [Link]();
Loan loan;
if ([Link]("HomeLoan")) {
loan = new HomeLoan(loanAmount);
} else if ([Link]("PersonalLoan")) {
loan = new PersonalLoan(loanAmount);
} else {
throw new IllegalArgumentException("Invalid Input");
[Link]();
} catch (Exception e) {
[Link]([Link]());
} finally {
[Link]();
Sample Input
5000
HomeLoan
Output
250.0