Beginner Level:
ques 1:
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int numStudents = [Link]();
int numSubjects = [Link]();
String[] studentNames = new String[numStudents];
double[][] grades = new double[numStudents][numSubjects];
for (int i = 0; i < numStudents; i++) {
[Link](); // To consume the leftover newline
studentNames[i] = [Link]();
for (int j = 0; j < numSubjects; j++) {
double grade;
try {
grade = [Link]();
} catch (InputMismatchException e) {
[Link]("Invalid grade entered for " +
studentNames[i]);
return;
}
if (grade < 0 || grade > 100) {
[Link]("Invalid grade entered for " +
studentNames[i]);
return;
} else {
grades[i][j] = grade;
}
}
}
double highestGrade = Double.MIN_VALUE;
double lowestGrade = Double.MAX_VALUE;
String highestGradeStudent = "";
String lowestGradeStudent = "";
[Link]("Average Grades:");
for (int i = 0; i < numStudents; i++) {
double sum = 0;
for (int j = 0; j < numSubjects; j++) {
sum += grades[i][j];
if (grades[i][j] > highestGrade) {
highestGrade = grades[i][j];
highestGradeStudent = studentNames[i];
}
if (grades[i][j] < lowestGrade) {
lowestGrade = grades[i][j];
lowestGradeStudent = studentNames[i];
}
}
double average = sum / numSubjects;
[Link]("%s: %.2f\n", studentNames[i], average);
}
// Corrected format specifiers for printing the highest and lowest grades
[Link]("Highest Grade: %.0f (%s)\n", highestGrade,
highestGradeStudent);
[Link]("Lowest Grade: %.0f (%s)\n", lowestGrade,
lowestGradeStudent);
[Link]();
}
}
ques 2:
import [Link];
public class Main {
private static final int REGULAR_HOURS = 160;
private static final double OVERTIME_MULTIPLIER = 1.5;
public static double calculateSalary(double hourlyWage, int hoursWorked) {
double totalSalary;
if (hoursWorked <= REGULAR_HOURS) {
totalSalary = hoursWorked * hourlyWage;
} else {
int overtimeHours = hoursWorked - REGULAR_HOURS;
totalSalary = (REGULAR_HOURS * hourlyWage) + (overtimeHours *
hourlyWage * OVERTIME_MULTIPLIER);
}
return totalSalary;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int numberOfEmployees = [Link]();
String[] employeeNames = new String[numberOfEmployees];
double[] hourlyWages = new double[numberOfEmployees];
int[] hoursWorked = new int[numberOfEmployees];
for (int i = 0; i < numberOfEmployees; i++) {
[Link]();
employeeNames[i] = [Link]();
hourlyWages[i] = [Link]();
hoursWorked[i] = [Link]();
}
for (int i = 0; i < numberOfEmployees; i++) {
double totalSalary = calculateSalary(hourlyWages[i], hoursWorked[i]);
[Link]("Total Salary: %.2f%n", totalSalary);
}
[Link]();
}
}
Intermediate Level:
ques 1:
import [Link];
class Car {
String type;
// Constructor
public Car(String type) {
[Link] = type;
}
// Method to calculate rental charges for standard car types
public double calculateRentalCharges(int days) {
double dailyRate;
switch ([Link]()) {
case "standard":
dailyRate = 2000;
break;
case "suv":
dailyRate = 4000;
break;
default:
dailyRate = 2000;
break;
}
return dailyRate * days;
}
// Overloaded method to calculate rental charges with additional options
public double calculateRentalCharges(int days, String... options) {
double baseCharge = calculateRentalCharges(days);
double optionsCharge = 0;
for (String option : options) {
switch ([Link]()) {
case "gps":
optionsCharge += 500 * days;
break;
case "child seat":
optionsCharge += 200 * days;
break;
default:
break;
}
}
return baseCharge + optionsCharge;
}
// Method to display car details and charges
public void displayRentalDetails(int days, String... options) {
double totalCharges = calculateRentalCharges(days, options);
[Link]([Link]("Total Rental Charges: ₹%.2f",
totalCharges));
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input car details
String type = [Link]().trim();
// Input number of days
int days = [Link]();
[Link]();
// Check for additional options input (optional)
String optionsInput = "";
if ([Link]()) {
optionsInput = [Link]().trim();
}
// Parse options if provided
String[] options = [Link]() ? new String[0] :
[Link](",\\s*");
// Create a Car object and calculate/display rental details
Car car = new Car(type);
[Link](days, options);
[Link]();
}
}
ques 2:
import [Link];
class BankAccount {
String accountHolderName;
int accountNumber;
double balance;
// Constructor
public BankAccount(String accountHolderName, int accountNumber, double
initialDeposit) {
[Link] = accountHolderName;
[Link] = accountNumber;
[Link] = initialDeposit;
}
// Method to display account details
public void displayAccountDetails() {
[Link]([Link]("Balance: ₹%.2f", balance));
}
}
class SavingsAccount extends BankAccount {
// Constructor
public SavingsAccount(String accountHolderName, int accountNumber, double
initialDeposit) {
super(accountHolderName, accountNumber, initialDeposit);
}
// Additional methods specific to SavingsAccount can be added here
}
class CurrentAccount extends BankAccount {
double overdraftLimit;
// Constructor
public CurrentAccount(String accountHolderName, int accountNumber, double
initialDeposit, double overdraftLimit) {
super(accountHolderName, accountNumber, initialDeposit);
[Link] = overdraftLimit;
}
// Method to display account details including overdraft limit
@Override
public void displayAccountDetails() {
[Link]();
[Link]([Link]("Overdraft Limit: ₹%.2f",
overdraftLimit));
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
String accountType = [Link]();
String accountHolderName = [Link]();
int accountNumber = [Link]();
double initialDeposit = [Link]();
if ([Link]("SavingsAccount")) {
SavingsAccount savingsAccount = new SavingsAccount(accountHolderName,
accountNumber, initialDeposit);
[Link]("Account Created: SavingsAccount for " +
[Link] +
" with Account Number " +
[Link]);
[Link]();
} else if ([Link]("CurrentAccount")) {
double overdraftLimit = [Link]();
CurrentAccount currentAccount = new CurrentAccount(accountHolderName,
accountNumber, initialDeposit, overdraftLimit);
[Link]("Account Created: CurrentAccount for " +
[Link] +
" with Account Number " +
[Link]);
[Link]();
} else {
[Link]("Invalid Account Type. Please enter either
SavingsAccount or CurrentAccount.");
}
[Link]();
}
}
ques 3:
import [Link];
// Enum for product categories
enum Category {
ELECTRONICS, CLOTHING, GROCERIES
}
// Interface for discountable products
interface Discountable {
double applyDiscount();
}
// Abstract Product class
abstract class Product implements Discountable {
String name;
double price;
Category category;
public Product(String name, double price, Category category) {
[Link] = name;
[Link] = price;
[Link] = category;
}
// Method to display product details
public void displayProductDetails() {
[Link]("Product: " + name);
[Link]("Category: " + category);
[Link]([Link]("Original Price: ₹%.2f", price));
[Link]([Link]("Discounted Price: ₹%.2f",
applyDiscount()));
}
}
// Electronics class that implements a discount strategy
class Electronics extends Product {
public Electronics(String name, double price) {
super(name, price, [Link]);
}
// 10% discount for electronics
@Override
public double applyDiscount() {
return price * 0.90; // 10% off
}
}
// Clothing class that implements a discount strategy
class Clothing extends Product {
public Clothing(String name, double price) {
super(name, price, [Link]);
}
// 20% discount for clothing
@Override
public double applyDiscount() {
return price * 0.80; // 20% off
}
}
// Groceries class that implements a discount strategy
class Groceries extends Product {
public Groceries(String name, double price) {
super(name, price, [Link]);
}
// 5% discount for groceries
@Override
public double applyDiscount() {
return price * 0.95; // 5% off
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input product details
String categoryInput = [Link]().trim().toUpperCase();
String productName = [Link]();
double productPrice = [Link]();
Product product = null;
// Create product based on the category
switch ([Link](categoryInput)) {
case ELECTRONICS:
product = new Electronics(productName, productPrice);
break;
case CLOTHING:
product = new Clothing(productName, productPrice);
break;
case GROCERIES:
product = new Groceries(productName, productPrice);
break;
default:
[Link]("Invalid category!");
break;
}
// If a valid product is created, display its details
if (product != null) {
[Link]();
}
[Link]();
}
}
Advance level
ques 1:
import [Link].*;
import [Link];
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
String fileName = [Link]().trim();
try {
int choice = [Link]();
[Link](); // Consume newline
if (choice == 1) {
// Writing to file
StringBuilder content = new StringBuilder();
String line;
while (!(line = [Link]()).equals("END")) {
[Link](line).append("\n");
}
writeFile(fileName, [Link]());
// Display content without trailing newline
String writtenContent = [Link]().trim();
[Link]("Written Content:\n" + writtenContent);
} else if (choice == 2) {
// Reading from file
String content = readFile(fileName);
// Display content without trailing newline
String readContent = [Link]();
[Link]("Read Content from File:\n" + readContent);
} else {
[Link]("Invalid choice. Please select 1 or 2.");
}
} catch (FileNotFoundException e) {
[Link]("Error Message: File not found. Please check the
file name and try again.");
} catch (IOException e) {
[Link]("Error Message: An I/O error occurred.");
} catch (SecurityException e) {
[Link]("Error Message: Access denied. You do not have the
necessary permissions.");
} finally {
[Link]();
}
}
private static void writeFile(String fileName, String content) throws
IOException {
try (FileWriter fileWriter = new FileWriter(fileName)) {
[Link](content);
}
}
private static String readFile(String fileName) throws IOException {
StringBuilder content = new StringBuilder();
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = [Link]()) != null) {
[Link](line).append("\n");
}
}
return [Link]();
}
}
ques 2:
import [Link];
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
String input = [Link]();
// Handle edge cases
if (input == null || [Link]()) {
throw new IllegalArgumentException("Input cannot be null or
empty.");
}
// Encrypt and decrypt the string
String encrypted = encrypt(input);
String decrypted = decrypt(encrypted);
[Link]("Encrypted String: " + encrypted);
[Link]("Decrypted String: " + decrypted);
} catch (IllegalArgumentException e) {
[Link]("Error: " + [Link]());
} catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());
} finally {
[Link]();
}
}
private static String encrypt(String input) {
// Apply Caesar cipher with shift of 3 positions
StringBuilder encrypted = new StringBuilder();
for (char ch : [Link]()) {
if ([Link](ch)) {
char base = [Link](ch) ? 'a' : 'A';
[Link]((char) ((ch - base + 3) % 26 + base));
} else if ([Link](ch)) {
[Link]((char) ((ch - '0' + 3) % 10 + '0'));
} else {
[Link](ch); // For non-alphanumeric characters, no change
}
}
// Reverse the encrypted string
return [Link]().toString();
}
private static String decrypt(String encrypted) {
// Reverse the string to get the original Caesar cipher result
StringBuilder reversed = new StringBuilder(encrypted).reverse();
// Apply reverse Caesar cipher with shift of 3 positions
StringBuilder decrypted = new StringBuilder();
for (char ch : [Link]().toCharArray()) {
if ([Link](ch)) {
char base = [Link](ch) ? 'a' : 'A';
[Link]((char) ((ch - base - 3 + 26) % 26 + base));
} else if ([Link](ch)) {
[Link]((char) ((ch - '0' - 3 + 10) % 10 + '0'));
} else {
[Link](ch); // For non-alphanumeric characters, no change
}
}
return [Link]();
}
}
ques 3:
import [Link].*;
import [Link].*;
import [Link].*;
public class Main {
private static final List<String> errorMessages =
[Link](new ArrayList<>());
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Read the number of files
int numFiles = [Link]();
[Link](); // Consume the newline
// Read the filenames
String[] fileNames = new String[numFiles];
for (int i = 0; i < numFiles; i++) {
fileNames[i] = [Link]();
}
// Determine if contents are provided directly after filenames
boolean contentProvidedDirectly = false;
List<String> fileContents = new ArrayList<>();
for (int i = 0; i < numFiles; i++) {
if ([Link]()) {
[Link]([Link]());
contentProvidedDirectly = true;
}
}
// Create a thread pool with a number of threads equal to the number of
input files
ExecutorService executor = [Link](numFiles);
List<Future<String>> futures = new ArrayList<>();
// Submit tasks for each file or simulated content
for (int i = 0; i < numFiles; i++) {
String fileName = fileNames[i];
if (contentProvidedDirectly) {
// If content is directly provided, process it as is
String content = [Link](i);
[Link]([Link](() -> processContent(fileName,
content)));
} else {
// Otherwise, attempt to read content from the file system
[Link]([Link](() -> processFile(fileName)));
}
}
// Shutdown the executor and wait for all tasks to complete
[Link]();
try {
if () {
[Link]();
}
} catch (InterruptedException e) {
[Link]();
[Link]().interrupt(); // Restore interrupted status
}
// Print results and error messages to stdout
for (Future<String> future : futures) {
try {
[Link]([Link]());
} catch (ExecutionException e) {
[Link]("Error processing file: " +
[Link]().getMessage());
} catch (InterruptedException e) {
[Link]().interrupt(); // Restore interrupted status
[Link]("Task was interrupted.");
}
}
// Print any error messages
if (![Link]()) {
try (PrintWriter writer = new PrintWriter(new
FileWriter("[Link]", true))) {
for (String errorMessage : errorMessages) {
[Link](errorMessage);
[Link](errorMessage);
}
} catch (IOException e) {
// Print the error for writing issues directly
[Link]("Error writing to [Link]: " +
[Link]());
}
}
[Link]();
}
// Method to process a file, read its content, and count words
private static String processFile(String fileName) {
try {
String content = readFile(fileName);
int wordCount = countWords(content);
return fileName + ": " + wordCount + " words";
} catch (IOException e) {
String errorMessage = "Error reading file: " + fileName;
[Link](errorMessage);
return errorMessage;
} catch (Exception e) {
String errorMessage = "Error processing file: " + fileName;
[Link](errorMessage);
return errorMessage;
}
}
// Method to simulate processing content directly provided
private static String processContent(String fileName, String content) {
try {
int wordCount = countWords(content);
return fileName + ": " + wordCount + " words";
} catch (Exception e) {
[Link]("Error processing content: " + fileName);
return "Error processing content: " + fileName;
}
}
// Method to read the content of a file
private static String readFile(String fileName) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
String line;
while ((line = [Link]()) != null) {
[Link](line).append(" ");
}
}
return [Link]().trim();
}
// Method to count words in the given content
private static int countWords(String content) {
return [Link]() ? 0 : [Link]("\\s+").length;
}
}
Expert level
ques 1:
import [Link];
import [Link];
import [Link];
class Student {
int id;
String name;
int age;
String major;
public Student(int id, String name, int age, String major) {
[Link] = id;
[Link] = name;
[Link] = age;
[Link] = major;
}
@Override
public String toString() {
return [Link]("ID: %d, Name: %s, Age: %d, Major: %s", id, name, age,
major);
}
}
public class Main {
// Static list to maintain state across operations
private static List<Student> students = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Display the menu
// Read the user's choice
int choice = [Link]([Link]());
switch (choice) {
case 1:
String addDetails = [Link]();
String[] addTokens = [Link]("\\s+");
addStudent(addTokens);
break;
case 2:
String deleteDetails = [Link]();
String[] deleteTokens = [Link]("\\s+");
deleteStudent(deleteTokens);
break;
case 3:
displayStudents();
break;
default:
[Link]("Invalid choice. Please try again.");
}
[Link]();
}
private static void addStudent(String[] tokens) {
try {
// Parse student details from the tokens
int id = [Link](tokens[0]);
String name = tokens[1];
int age = [Link](tokens[2]);
String major = tokens[3];
// Check if a student with the same ID already exists
if ([Link]().anyMatch(student -> [Link] == id)) {
[Link]("A student with this ID already exists. Please
use a unique ID.");
return;
}
// Add student to the list
Student student = new Student(id, name, age, major);
[Link](student);
[Link]("Student added: " + student);
} catch (Exception e) {
[Link]("Error adding student. Please ensure you enter the
details in the correct format.");
}
}
private static void deleteStudent(String[] tokens) {
try {
// Parse student ID to delete
int id = [Link](tokens[0]);
// Find and remove the student by ID
boolean found = [Link](student -> [Link] == id);
if (found) {
[Link]("Student with ID " + id + " is deleted.");
} else {
[Link]("Student not found.");
}
} catch (Exception e) {
[Link]("Error deleting student. Please ensure you enter a
valid ID.");
}
}
private static void displayStudents() {
if ([Link]()) {
[Link]("No students available.");
} else {
[Link]("List of students:");
for (Student student : students) {
[Link](student);
}
}
}
}
ques 2:
import [Link];
// The public class should be named Main and match the filename [Link]
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Display the menu to the user
int choice = [Link]();
if (choice == 1) {
// CustomLinkedList operations
CustomLinkedList linkedList = new CustomLinkedList();
for (int i = 0; i < 3; i++) {
[Link]([Link]());
}
[Link](); // Consume newline
[Link]("Linked List after additions:");
[Link]();
int removeIndex = [Link]();
[Link](removeIndex);
[Link]("Linked List after removal:");
[Link]();
int getIndex = [Link]();
[Link]("Element at index " + getIndex + ": " +
[Link](getIndex));
[Link]("Size of the LinkedList: " + [Link]());
} else if (choice == 2) {
// CustomStack operations
CustomStack stack = new CustomStack();
for (int i = 0; i < 3; i++) {
[Link]([Link]());
}
[Link]("Stack after pushes:");
[Link]();
[Link]("Popped elements: ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
try {
[Link]([Link]()).append(" ");
} catch (IllegalStateException e) {
[Link]([Link]());
}
}
// Print the result with a trailing space removed
[Link]([Link]().trim());
[Link]("Stack after pops:");
[Link]();
} else {
[Link]("Invalid choice.");
}
[Link]();
}
// Inner class CustomLinkedList
static class CustomLinkedList {
private Node head;
private int size;
private class Node {
int data;
Node next;
Node(int data) {
[Link] = data;
[Link] = null;
}
}
public CustomLinkedList() {
head = null;
size = 0;
}
// Add element at the end
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while ([Link] != null) {
current = [Link];
}
[Link] = newNode;
}
size++;
}
// Remove element at specific index
public void remove(int index) {
if (index < 0 || index >= size) {
[Link]("Index out of bounds.");
return;
}
if (index == 0) {
head = [Link];
} else {
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = [Link];
}
[Link] = [Link];
}
size--;
}
// Get element at specific index
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds.");
}
Node current = head;
for (int i = 0; i < index; i++) {
current = [Link];
}
return [Link];
}
// Get size of the list
public int size() {
return size;
}
// Display the list
public void display() {
Node current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
[Link]([Link]);
current = [Link];
if (current != null) {
[Link](" "); // Append space only if there's another node
after the current one
}
}
[Link]([Link]());
}
}
// Inner class CustomStack
static class CustomStack {
private CustomLinkedList list;
public CustomStack() {
list = new CustomLinkedList();
}
// Push element onto the stack
public void push(int data) {
[Link](data);
}
// Pop element from the stack
public int pop() {
if ([Link]() == 0) {
throw new IllegalStateException("Stack underflow.");
}
int data = [Link]([Link]() - 1);
[Link]([Link]() - 1);
return data;
}
// Peek element from the stack
public int peek() {
if ([Link]() == 0) {
throw new IllegalStateException("Stack is empty.");
}
return [Link]([Link]() - 1);
}
// Get size of the stack
public int size() {
return [Link]();
}
// Display the stack
public void display() {
[Link]();
}
}
}
ques 3:
import [Link];
import [Link];
import [Link];
import [Link];
class Book {
private int id;
private String title;
private String author;
private int year;
public Book(int id, String title, String author, int year) {
[Link] = id;
[Link] = title;
[Link] = author;
[Link] = year;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
@Override
public String toString() {
return "ID: " + id + ", Title: " + title + ", Author: " + author + ", Year:
" + year;
}
}
class Library {
private Map<Integer, Book> booksById;
private TreeMap<String, Book> booksByTitle;
public Library() {
booksById = new HashMap<>();
booksByTitle = new TreeMap<>();
}
public void addBook(Book book) {
[Link]([Link](), book);
[Link]([Link](), book);
}
public void removeBookById(int id) {
Book book = [Link](id);
if (book != null) {
[Link]([Link]());
}
}
public Book searchById(int id) {
return [Link](id);
}
public Book searchByTitle(String title) {
return [Link](title);
}
public void displayBooksSortedByTitle() {
for ([Link]<String, Book> entry : [Link]()) {
[Link]([Link]());
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Library library = new Library();
// Read the number of books to add
int numBooks = [Link]([Link]().trim());
// Add books
for (int i = 0; i < numBooks; i++) {
String[] bookDetails = [Link]().split(", ");
int id = [Link](bookDetails[0].split("=")[1].trim());
String title = bookDetails[1].split("=")[1].trim();
String author = bookDetails[2].split("=")[1].trim();
int year = [Link](bookDetails[3].split("=")[1].trim());
[Link](new Book(id, title, author, year));
}
// Display books sorted by title
[Link]("Books sorted by title:");
[Link]();
// Search books by ID
int searchId = [Link]([Link]().trim());
[Link]("Search ID " + searchId + ":");
[Link]([Link](searchId));
// Remove a book by ID
int removeId = [Link]([Link]().trim());
[Link](removeId);
[Link]("Removed book with ID " + removeId);
// Display books sorted by title again
[Link]("Books sorted by title after removal:");
[Link]();
[Link]();
}
}