0% found this document useful (0 votes)
27 views30 pages

Winsem2024-25 Bcse103e Ela VL2024250505256 Model-Question-Paper

The document outlines a series of Java programming tasks, including the use of logical, bitwise, and relational operators, as well as array and class manipulations. It covers various applications such as login systems, student eligibility checks, permission management, employee evaluations, and data handling for e-commerce and banking systems. Additionally, it includes tasks related to file handling and object-oriented programming concepts like inheritance and abstraction.

Uploaded by

srigowri.ojjala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views30 pages

Winsem2024-25 Bcse103e Ela VL2024250505256 Model-Question-Paper

The document outlines a series of Java programming tasks, including the use of logical, bitwise, and relational operators, as well as array and class manipulations. It covers various applications such as login systems, student eligibility checks, permission management, employee evaluations, and data handling for e-commerce and banking systems. Additionally, it includes tasks related to file handling and object-oriented programming concepts like inheritance and abstraction.

Uploaded by

srigowri.ojjala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Part A

1. Write a Java Program to test the logical operators. Use short-circuit evaluation?.
Imagine you're building a login system where you validate user credentials. Use short-
circuiting ( and && ) plays a crucial role.

2. Write a Java Program to test the logical operators. Use short-circuit evaluation?.
Imagine you're building a login system where you validate user credentials. Use short-
circuiting ( and || ) plays a crucial role.

3. Given a set of rules for student eligibility (minimum attendance of 75% and a passing
grade of at least 50%), write a Java program that checks whether a student qualifies
using logical operators

4. Bitwise operators can be useful for managing permissions in systems where multiple
flags are combined efficiently. Read (0001 → 1), Write(0010 → 2) Execute (0100→4),
Delete ((1000 → 8). Use scanner to get the User name (String) and their permission
level (4 bit binary value by addition of all 1111). Display the User name and Permission
type. Ask a question to revoke and disable any permission. After the execution, display
the status.

5. Bitwise operators can be useful for managing permissions in systems where multiple
flags are combined efficiently. View Account (0001 → 1), Withdraw Funds(0010 → 2)
Transfer Funds (0100→4), Close Account ((1000 → 8). Use scanner to get the User
name (String) and their permission level (4 bit binary value by addition of all 1111).
Display the User name and Permission type. Ask a question to revoke and disable any
permission. After the execution, display the status.

6. Relational operators in Java (==, !=, >, <, >=, <=) help in comparing values and making
decisions. Write a Java program for a student grade evaluation system where relational
operators determine pass/fail status and grade classification

7. Instead of student grading, let’s create an employee performance evaluation system that
categorizes employees based on their annual performance score using relational
operators. Performance Classification Rules (Outstanding: Score >= 90, Exceeds
Expectations: Score >= 75 and < 90, Meets Expectations: Score >= 50 and < 75, Needs
Improvement: Score < 50) The program will take employee name and score, evaluate
their performance category, and determine whether they qualify for a bonus.

8. Imagine you are building a simple employee database where users can search for an
employee ID from an array of employee records. The program will: store employee
IDs in an array, allow the user to search for an ID, if found display the result.
9. Developing an e-commerce platform, where product prices need to be sorted to help
customers view items in ascending order (lowest to highest) or descending order
(highest to lowest). Sorting ensures better price comparisons and enhances user
experience. Write a java program which sorts the price based on the user input
ascending or descending order which is stored in an array.

10. Calculate students’ average scores, highest score, lowest score using array passing to
methods. User inputs the number of students and creates an array dynamically. Enter
the scores. Call for a method which processes the array like average scores, highest
score, lowest score and display the value

11. Designing an employee attendance tracking system where each row in a 2D array
represents an employee, and each column represents their attendance for a particular
week. The program will: store attendance records in a 2D array (1 for Present, 0 for
Absent), pass the 2D array to methods to calculate, Total attendance per employee.
Display the attendance status for each employee

12. A jagged array is useful when different groups of data have varying lengths. For
example, in a university system, students may take different numbers of exams
depending on their subject choices. Write a java program which handles jagged array
for student scores.

13. A Business sales tracking system, where sales data for different departments is recorded
for each month. Rows representing departments, columns representing monthly sales
figures. Using an enhanced for loop to the 2d array, display each department’s sales,
calculate the total sales for each department and overall company sales.

14. The program takes a 5x5 input and outputs the same in a transposed matrix. Write a
Java program which takes the 5x5 input, the value varies between 0 -255 for each input
and transposed output is displayed.

15. An anagram is a word or a phrase made by transposing the letters of another word or
phrase; for example, "parliament" is an anagram of "partial men," and "software" is an
anagram of "swear oft." Write a program that figures out whether one string is an
anagram of another string. The program should ignore white space and punctuation.

16. Write a Java program that takes a number as input and prints its equivalent as
Binary, Hexadecimal, Octal number based on the CASE input through the scanner
statement.

17. Write a Java program which receives an encryption key to shift the alphabets value in
a Caesar cipher and the plain text message is encrypted and vice versa in decryption
process of an encrypted message back to the given plaintext message?
18. Write a Java program which receives a series of String inputs which is stored in a string
array. The program should receive a character input from the user to find and replace
the substring (Character replace ar with xy Chxyacter) with another character in the
String array.

Part B

1. A class called circle is designed as following. It contains: Two private instance


variables: radius (of the type double) and color (of the type String), with default
value of 1.0 and "red", respectively. Two overloaded constructors - a default
constructor with no argument, and a constructor which takes a double argument
for radius and color. Two public methods: getRadius() and getArea(), which return
the radius and area of this instance, respectively.

2. A class called rectangle is designed as following. It contains: Three private


instance variables: length & breath (of the type double) and color (of the type
String), with default value of 5.0 & 7.0 and "red", respectively. Two overloaded
constructors - a default constructor with no argument, and a constructor which
takes a double argument for radius and color. Two public methods:
getLengthBreath(), getPerimeter(), getColor(), and getArea(), which return the
length breath, perimeter, color and area of this instance, respectively.

3. Abstract Superclass Shape and Its Concrete Subclasses. The superclass Shape
and its subclasses Circle, Rectangle and Square are as follows. Shape is an
abstract class containing 2 abstract methods: getArea() and getPerimeter(), where
its concrete subclasses must provide its implementation. All instance variables
shall have protected access, i.e., accessible by its subclasses and classes in the
same package. Mark all the overridden methods with annotation @Override.

4. Abstract Superclass Shape and Its Concrete Subclasses. How would you design
the vehicle superclass and ensure its subclasses (car, bike, and truck ) implement
getMaxSpeed() and getFuelEfficiency(). All instance variables shall have
protected access, i.e., accessible by its subclasses and classes in the same
package. Mark all the overridden methods with annotation @Override.

5. Design a class to represent a bank account. Include the following members

Data Members
(a) Name of the depositor,
(b) account number,
(c) Type of account
(d) Balance amount in the account
Methods
To assign initial values
To deposit an amount
To withdraw an amount after checking the balance
To display the name and balance

6. An educational institution wishes to maintain a database of its employee. The


database is divided into a few classes whose hierarchical relationships are
shown. The figures also show the minimum information required for each class.
Specify all the classes and define methods to create the database and retrieve
individual information as and when required.

Write a java program to write the following into the text file in the following format.
@12% for food items
@18% non food items
Bill.txt
Grocery Bill No. :2025-03-001
Customer Name : R. Sivacoumar
Customer Phone : 9952840844
___________________________________________________________________________
_____
Sl. No. Item Name Quantity Purchased Unit Value Total Amount
GST
___________________________________________________________________________
_____
1 Onion kg 4 25.00 100.00
12.00
2 Atta kg 2 49.00 98.00
11.76
3 Sunflower oil L 2 123.50
4 Jam Mixed nos 1 185.00
5 Detergent kg 1.5 1450.00
___________________________________________________________________________
_____
Total 221.76 (including GST)
___________________________________________________________________________
_____

7. Write a java program to search for an item in csv file and include in a bill.
Bill.txt should be like the below. You can manually create a CSV file with the item
list and unit price only. In the main program, input the Item Code, Purchase
Quantity,

@12% for food items


@18% non food items
Bill.txt
Grocery Bill No. :2025-03-001
Customer Name : R. Sivacoumar
Customer Phone : 9952840844
___________________________________________________________________________
_____
Item Code Item Name Quantity Purchased Unit Value Total Amount
GST
___________________________________________________________________________
_____
FC101 Onion kg 4 25.00 100.00
12.00
FC102 Atta kg 2 49.00 98.00
11.76
FC103 Sunflower oil L 2 123.50
FC104 Jam Mixed nos 1 185.00
NC105 Detergent kg 1.5 1450.00

___________________________________________________________________________
_____
Total 221.76 (including GST)
___________________________________________________________________________
_____

8. A person is investing in LIC Rs.5000 every year. Write a Java program to calculate the
total returns (a) If he has paid the full term of 20 years and acquired bonus at a rate of
10 % after every 5 years. The accumulated sum after every year is 1.5 % compound
interest for first years and increase of 2 % after 5 years thereafter. Calculate the total
assured sum after 20 years

9. A person deposits ₹10,000 per year into a fixed deposit scheme with a compound
interest rate of 5% annually. The scheme includes: Bonus: A loyalty bonus of
₹2,000 every 4 years. Penalty: If the person withdraws before 15 years, a 2%
annual penalty is deducted. Write a Java program that calculates the total amount
accumulated for a full 15-year deposit term. A case where the deposit is stopped
after 10 years and penalties apply. Output should be stored in a csv format table.

10. Write a Java program which uses Classes, Object, passing objects to methods.
Convert the given cartesian (5,4,2) to spherical co-ordinates (ρ = √(x2 + y2 + z2)
θ = tan-1(y/x), φ = cos-1(z/√(x2 + y2 + z2)), Write the output to a txt file named
spherical.txt

11. A company maintains a hierarchical employee structure, where different roles


inherit from a Superclass Employee -> (name, Salary), Subclasses Manager and
Developer -> inherit from Employee and add role specific attributes. Further,
Senior Manager extends Manager ->additional leadership role. Software Engineer
extends Developer -> additional role in Software maintenance. Write a Java
program implementing hierarchical inheritance for the above.
Key for FAT Questions A part

19. Write a Java Program to test the logical operators. Use short-circuit evaluation?.
Imagine you're building a login system where you validate user credentials. Use short-
circuiting ( and && ) plays a crucial role.

package sample1;

import java.util.Scanner;
public class ShortCircuitLogin {
public static void main(String[] args) {
String correctUsername = "admin";
String correctPassword = "secure123";
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String inputUsername = scanner.nextLine();
System.out.print("Enter password: ");
String inputPassword = scanner.nextLine();
// Short-circuiting prevents password check if username is incorrect
if (inputUsername.equals(correctUsername) &&
inputPassword.equals(correctPassword)) {
System.out.println("Login successful!");
} else {

System.out.println("Invalid login credentials.");


}
scanner.close();
}
}
20. Write a Java Program to test the logical operators. Use short-circuit evaluation?.
Imagine you're building a login system where you validate user credentials. Use short-
circuiting ( or || ) plays a crucial role. (if username “admin” then password need not
be checked else check password also)

package sample1;

import java.util.Scanner;
public class ShortCircuitLogin {
public static void main(String[] args) {
String correctUsername = "admin";
String correctPassword = "secure123";
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String inputUsername = scanner.nextLine();
System.out.print("Enter password: ");
String inputPassword = scanner.nextLine();
// Short-circuiting prevents password check if username is incorrect
if (inputUsername.equals("admin") || inputPassword.equals("override123")) {
System.out.println("Admin access granted!");
}else {

System.out.println("Invalid login credentials.");


}
scanner.close();
}
}
21. Given a set of rules for student eligibility (minimum attendance of 75% and a passing
grade of at least 50%), write a Java program that checks whether a student qualifies
using logical operators
package sample1;

import java.util.Scanner;

public class StudentEligibility {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking user input
System.out.print("Enter attendance percentage: ");
double attendance = scanner.nextDouble();

System.out.print("Enter grade percentage: ");


double grade = scanner.nextDouble();

// Checking eligibility using logical AND (&&)


boolean isEligible = (attendance >= 75) && (grade >= 50);

// Display result
if (isEligible) {
System.out.println("Student qualifies for eligibility.");
} else {
System.out.println("Student does NOT qualify.");
if (attendance < 75) {
System.out.println("Reason: Insufficient attendance.");
}
if (grade < 50) {
System.out.println("Reason: Low grade.");
}
}
scanner.close();
}
}

22. Bitwise operators can be useful for managing permissions in systems where multiple
flags are combined efficiently. Read (0001 → 1), Write(0010 → 2) Execute (0100→4),
Delete ((1000 → 8). Use scanner to get the User name (String) and their permission
level (4 bit binary value by addition of all 1111). Display the User name and Permission
type. Ask a question to revoke and disable any permission. After the execution, display
the status.

package sample1;

import java.util.Scanner;

public class Permission{


// Define permission constants
public static final int READ = 1; // 0001 (Binary)
public static final int WRITE = 2; // 0010 (Binary)
public static final int EXECUTE = 4; // 0100 (Binary)
public static final int DELETE = 8; // 1000 (Binary)

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Get user name


System.out.print("Enter User Name: ");
String userName = scanner.nextLine();

// Get user's permission level as a binary sum


System.out.print("Enter permission level (Sum of binary values like 15
for 1111): ");
int permissions = scanner.nextInt();

// Display initial permissions


System.out.println("\nUser: " + userName);
System.out.println("Initial Permissions:");
displayPermissions(permissions);

// Ask user to revoke a permission


System.out.println("\nEnter permission to revoke:");
System.out.println("1 - Read, 2 - Write, 4 - Execute, 8 - Delete");
System.out.print("Choice: ");
int revokePermission = scanner.nextInt();

// Revoke permission using bitwise operation


permissions &= ~revokePermission;

// Display updated permissions


System.out.println("\nUpdated Permissions:");
displayPermissions(permissions);

scanner.close();
}

// Method to display active permissions


public static void displayPermissions(int permissions) {
System.out.println("Read: " + ((permissions & READ) != 0 ? "Allowed"
: "Not Allowed"));
System.out.println("Write: " + ((permissions & WRITE) != 0 ?
"Allowed" : "Not Allowed"));
System.out.println("Execute: " + ((permissions & EXECUTE) != 0 ?
"Allowed" : "Not Allowed"));
System.out.println("Delete: " + ((permissions & DELETE) != 0 ?
"Allowed" : "Not Allowed"));
}
}

23. Bitwise operators can be useful for managing permissions in systems where multiple
flags are combined efficiently. View Account (0001 → 1), Withdraw Funds(0010 → 2)
Transfer Funds (0100→4), CloseAccount ((1000 → 8). Use scanner to get the User
name (String) and their permission level (4 bit binary value by addition of all 1111).
Display the User name and Permission type. Ask a question to revoke and disable any
permission. After the execution, display the status.

package sample1;

import java.util.Scanner;

public class AccessControl {


// Define permission constants
public static final int VIEW_ACCOUNT = 1; // 0001 (Binary)
public static final int WITHDRAW_FUNDS = 2; // 0010 (Binary)
public static final int TRANSFER_MONEY = 4; // 0100 (Binary)
public static final int CLOSE_ACCOUNT = 8; // 1000 (Binary)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get user details
System.out.print("Enter User Name: ");
String userName = scanner.nextLine();
System.out.print("Enter access level (Sum of binary values like 15 for 1111): ");
int accessLevel = scanner.nextInt();
// Display initial permissions
System.out.println("\nUser: " + userName);
System.out.println("Initial Access Rights:");
displayAccessRights(accessLevel);
// Ask user to revoke an access right
System.out.println("\nEnter the access level to revoke:");
System.out.println("1 - View Account, 2 - Withdraw Funds, 4 - Transfer Money,
8 - Close Account");
System.out.print("Choice: ");
int revokeAccess = scanner.nextInt();

// Revoke permission using bitwise operation


accessLevel &= ~revokeAccess;

// Display updated access rights


System.out.println("\nUpdated Access Rights:");
displayAccessRights(accessLevel);

scanner.close();
}
// Method to display active access rights
public static void displayAccessRights(int accessLevel) {
System.out.println("View Account: " + ((accessLevel & VIEW_ACCOUNT) !=
0 ? "Allowed" : " Not Allowed"));
System.out.println("Withdraw Funds: " + ((accessLevel &
WITHDRAW_FUNDS) != 0 ? "Allowed" : " Not Allowed"));
System.out.println("Transfer Money: " + ((accessLevel &
TRANSFER_MONEY) != 0 ? " Allowed" : " Not Allowed"));
System.out.println("Close Account: " + ((accessLevel & CLOSE_ACCOUNT)
!= 0 ? " Allowed" : " Not Allowed"));
}
}

5. Relational operators in Java (==, !=, >, <, >=, <=) help in comparing values and making
decisions. Write a Java program for a student grade evaluation system where relational
operators determine pass/fail status and grade classification

package sample1;

import java.util.Scanner;

public class Template {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get student details


System.out.print("Enter Student Name: ");
String studentName = scanner.nextLine();

System.out.print("Enter Student Score (0-100): ");


int score = scanner.nextInt();
// Relational checks
boolean isPassed = score >= 50; // Student must score at least 50 to pass
boolean isOutstanding = score > 90; // Outstanding if score > 90
boolean isAboveAverage = score >= 75; // Above Average if score is 75 or more
boolean isBelowAverage = score < 50; // Below Average if less than 50

// Display results
System.out.println("\nStudent: " + studentName);
System.out.println("Score: " + score);
System.out.println("Pass Status: " + (isPassed ? "✅ Passed" : "❌ Failed"));

// Grade classification using relational operators


if (isOutstanding) {
System.out.println("Performance: 🌟 Outstanding");
} else if (isAboveAverage) {
System.out.println("Performance: 👍 Above Average");
} else if (isBelowAverage) {
System.out.println("Performance: ❌ Below Average");
} else {
System.out.println("Performance: ✅ Average");
}

scanner.close();
}
}

6. Instead of student grading, let’s create an employee performance evaluation system that
categorizes employees based on their annual performance score using relational
operators. Performance Classification Rules (Outstanding: Score >= 90, Exceeds
Expectations: Score >= 75 and < 90, Meets Expectations: Score >= 50 and < 75, Needs
Improvement: Score < 50) The program will take employee name and score, evaluate
their performance category, and determine whether they qualify for a bonus.

package sample1;

import java.util.Scanner;

public class EmployeeEvaluation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get employee details
System.out.print("Enter Employee Name: ");
String employeeName = scanner.nextLine();

System.out.print("Enter Performance Score (0-100): ");


int score = scanner.nextInt();

// Relational checks
boolean isOutstanding = score >= 90;
boolean exceedsExpectations = score >= 75 && score < 90;
boolean meetsExpectations = score >= 50 && score < 75;
boolean needsImprovement = score < 50;
boolean qualifiesForBonus = score >= 75; // Employees with 75+ score get a
bonus

// Display results
System.out.println("\nEmployee: " + employeeName);
System.out.println("Performance Score: " + score);

if (isOutstanding) {
System.out.println("Rating: 🌟 Outstanding");
} else if (exceedsExpectations) {
System.out.println("Rating: 👍 Exceeds Expectations");
} else if (meetsExpectations) {
System.out.println("Rating: ✅ Meets Expectations");
} else {
System.out.println("Rating: ❌ Needs Improvement");
}

// Display bonus eligibility


System.out.println("Bonus Eligibility: " + (qualifiesForBonus ? "🎉 Eligible" :
"❌ Not Eligible"));

scanner.close();
}
}
7. Imagine you are building a simple employee database where users can search for an
employee ID from an array of employee records. The program will: store employee
IDs in an array, allow the user to search for an ID, if found display the result.

package sample1;
import java.util.Scanner;
public class EmployeeSearch {
public static void main(String[] args) {
// Example employee ID database
int[] employeeIDs = {101, 203, 305, 408, 512};

// Scanner for user input


Scanner scanner = new Scanner(System.in);
// Get Employee ID to search
System.out.print("Enter Employee ID to search: ");
int searchID = scanner.nextInt();
// Search for ID using linear search
boolean found = false;
for (int id : employeeIDs) {
if (id == searchID) {
found = true;
break;
}
}
// Display search result
if (found) {
System.out.println("✅ Employee ID " + searchID + " found in the
database.");
} else {
System.out.println("❌ Employee ID " + searchID + " NOT found in the
database.");
}
scanner.close();
}
}
8. Developing an e-commerce platform, where product prices need to be sorted to help
customers view items in ascending order (lowest to highest) or descending order
(highest to lowest). Sorting ensures better price comparisons and enhances user
experience. Write a java program which sorts the price based on the user input
ascending or descending order which is stored in an array.

package sample1;
import java.util.Arrays;
import java.util.Scanner;

public class PriceSorter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Example product prices
double[] prices = {1299.99, 499.50, 799.75, 199.99, 1599.99};

// Display original prices


System.out.println("Original Product Prices:");
System.out.println(Arrays.toString(prices));

// Ask the user for sorting preference


System.out.print("\nEnter sorting order (1 for Ascending, 2 for Descending): ");
int order = scanner.nextInt();
// Sort the array
if (order == 1) {
Arrays.sort(prices); // Ascending order
} else {
Arrays.sort(prices);
reverseArray(prices); // Reverse for Descending order
}

// Display sorted prices


System.out.println("\nSorted Product Prices:");
System.out.println(Arrays.toString(prices));

scanner.close();
}
// Method to reverse array for descending order
public static void reverseArray(double[] arr) {
int n = arr.length;
for (int i = 0; i < n / 2; i++) {
double temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
}
}

9. Calculate students’ average scores, highest score, lowest score using array passing to
methods. User inputs the number of students and creates an array dynamically. Enter
the scores. Call for a method which processes the array like average scores, highest
score, lowest score and display the value

package sample1;
import java.util.Scanner;

public class StudentScores {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get number of students


System.out.print("Enter number of students: ");
int n = scanner.nextInt();
double[] scores = new double[n];

// Input scores
System.out.println("Enter the scores:");
for (int i = 0; i < n; i++) {
System.out.print("Student " + (i + 1) + ": ");
scores[i] = scanner.nextDouble();
}

// Pass array to method and display results


double averageScore = calculateAverage(scores);
double highestScore = findHighest(scores);
double lowestScore = findLowest(scores);

System.out.println("\nResults:");
System.out.println("Average Score: " + averageScore);
System.out.println("Highest Score: " + highestScore);
System.out.println("Lowest Score: " + lowestScore);

scanner.close();
}

// Method to calculate average


public static double calculateAverage(double[] scores) {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.length;
}

// Method to find highest score


public static double findHighest(double[] scores) {
double max = scores[0];
for (double score : scores) {
if (score > max) {
max = score;
}
}
return max;
}

// Method to find lowest score


public static double findLowest(double[] scores) {
double min = scores[0];
for (double score : scores) {
if (score < min) {
min = score;
}
}
return min;
}
}

10. Calculate students’ average scores, highest score, lowest score using array passing to
methods. User inputs the number of students and creates an array dynamically. Enter
the scores. Call for a method which processes the array like average scores, highest
score, lowest score and display the value
package sample1;
import java.util.Scanner;

public class StudentScores {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get number of students


System.out.print("Enter number of students: ");
int n = scanner.nextInt();
double[] scores = new double[n];

// Input scores
System.out.println("Enter the scores:");
for (int i = 0; i < n; i++) {
System.out.print("Student " + (i + 1) + ": ");
scores[i] = scanner.nextDouble();
}

// Pass array to method and display results


double averageScore = calculateAverage(scores);
double highestScore = findHighest(scores);
double lowestScore = findLowest(scores);

System.out.println("\nResults:");
System.out.println("Average Score: " + averageScore);
System.out.println("Highest Score: " + highestScore);
System.out.println("Lowest Score: " + lowestScore);

scanner.close();
}

// Method to calculate average


public static double calculateAverage(double[] scores) {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.length;
}
// Method to find highest score
public static double findHighest(double[] scores) {
double max = scores[0];
for (double score : scores) {
if (score > max) {
max = score;
}
}
return max;
}

// Method to find lowest score


public static double findLowest(double[] scores) {
double min = scores[0];
for (double score : scores) {
if (score < min) {
min = score;
}
}
return min;
}
}

11. Designing an employee attendance tracking system where each row in a 2D array
represents an employee, and each column represents their attendance for a particular
week. The program will: store attendance records in a 2D array (1 for Present, 0 for
Absent), pass the 2D array to methods to calculate, Total attendance per employee.
Display the attendance status for each employee
package sample1;
import java.util.Scanner;

public class EmployeeAttendance {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Define number of employees and days


System.out.print("Enter number of employees: ");
int employees = scanner.nextInt();
System.out.print("Enter number of days in a week: ");
int days = scanner.nextInt();

int[][] attendance = new int[employees][days];

// Input attendance (1 for present, 0 for absent)


System.out.println("\nEnter attendance records (1 = Present, 0 = Absent):");
for (int i = 0; i < employees; i++) {
System.out.println("Employee " + (i + 1) + ":");
for (int j = 0; j < days; j++) {
System.out.print("Day " + (j + 1) + ": ");
attendance[i][j] = scanner.nextInt();
}
}

// Pass 2D array to methods


displayAttendance(attendance);
calculateEmployeeAttendance(attendance);
calculateOverallAttendance(attendance);

scanner.close();
}

// Method to display attendance records


public static void displayAttendance(int[][] attendance) {
System.out.println("\nAttendance Records:");
for (int i = 0; i < attendance.length; i++) {
System.out.print("Employee " + (i + 1) + ": ");
for (int j = 0; j < attendance[i].length; j++) {
System.out.print(attendance[i][j] + " ");
}
System.out.println();
}
}

// Method to calculate individual attendance


public static void calculateEmployeeAttendance(int[][] attendance) {
System.out.println("\nTotal Attendance Per Employee:");
for (int i = 0; i < attendance.length; i++) {
int count = 0;
for (int j = 0; j < attendance[i].length; j++) {
count += attendance[i][j]; // Sum up present days
}
System.out.println("Employee " + (i + 1) + ": " + count + " days present");
}
}

// Method to calculate overall company attendance


public static void calculateOverallAttendance(int[][] attendance) {
int totalDaysPresent = 0;
int totalEntries = attendance.length * attendance[0].length;

for (int i = 0; i < attendance.length; i++) {


for (int j = 0; j < attendance[i].length; j++) {
totalDaysPresent += attendance[i][j];
}
}
System.out.println("\nOverall Company Attendance: " + totalDaysPresent + "/"
+ totalEntries + " days present");
}
}

12. A jagged array is useful when different groups of data have varying lengths. For
example, in a university system, students may take different numbers of exams
depending on their subject choices. Write a java program which handles jagged array
for student scores.

package sample1;
import java.util.Scanner;

public class JaggedArrayExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Define number of students


System.out.print("Enter number of students: ");
int students = scanner.nextInt();

// Create a jagged array for student scores


int[][] scores = new int[students][];

// Input number of exams per student and their scores


for (int i = 0; i < students; i++) {
System.out.print("\nEnter number of exams taken by Student " + (i +
1) + ": ");
int exams = scanner.nextInt();
scores[i] = new int[exams]; // Allocate variable-sized array

for (int j = 0; j < exams; j++) {


System.out.print("Enter score for Exam " + (j + 1) + ": ");
scores[i][j] = scanner.nextInt();
}
}

// Display student scores


System.out.println("\nStudent Exam Scores:");
for (int i = 0; i < scores.length; i++) {
System.out.print("Student " + (i + 1) + ": ");
for (int j = 0; j < scores[i].length; j++) {
System.out.print(scores[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}

13. A Business sales tracking system, where sales data for different departments is recorded
for each month. Rows representing departments, columns representing monthly sales
figures. Using an enhanced for loop to the 2d array, display each department’s sales,
calculate the total sales for each department and overall company sales.

package sample1;
public class SalesReport{
public static void main(String[] args) {
// Define department names
String[] departments = {"Electronics", "Clothing", "Groceries"};

// Define month names


String[] months = {"January", "February", "March"};

// 2D array representing sales data for each department over 3 months


int[][] sales = {
{1200, 1500, 1700}, // Electronics
{2000, 2100, 2500}, // Clothing
{1800, 1900, 2100} // Groceries
};

System.out.println("Monthly Sales Report:");

int totalCompanySales = 0; // Track overall sales

// Enhanced for loop to iterate through departments


for (int i = 0; i < sales.length; i++) {
int departmentTotal = 0;
System.out.println("\nDepartment: " + departments[i]);

// Enhanced for loop to iterate through monthly sales


for (int j = 0; j < sales[i].length; j++) {
System.out.println(months[j] + ": $" + sales[i][j]);
departmentTotal += sales[i][j]; // Sum monthly sales for each
department
}

System.out.println("Total Sales: $" + departmentTotal);


totalCompanySales += departmentTotal;
}

System.out.println("\nOverall Company Sales: $" + totalCompanySales);


}
}
14. The program takes a 5x5 input and outputs the same in a transposed matrix. Write a
Java program which takes the 5x5 input, the value varies between 0 -255 for each input
and transposed output is displayed.
package sample1;
import java.util.Scanner;

public class Template {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get matrix size


System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

// Create matrix
int[][] matrix = new int[rows][cols];

// Input matrix elements


System.out.println("Enter matrix elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Compute transpose
int[][] transposed = new int[cols][rows]; // Swap row and column sizes
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j]; // Transposing
}
}

// Display transposed matrix


System.out.println("\nTransposed Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transposed[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}
1. A class called circle is designed as following. It contains: Two private instance
variables: radius (of the type double) and color (of the type String), with default
value of 1.0 and "red", respectively. Two overloaded constructors - a default
constructor with no argument, and a constructor which takes a double argument
for radius and color. Two public methods: getRadius() and getArea(), which return
the radius and area of this instance, respectively.

package sample1;
public class Circle {
// Private instance variables
private double radius;
private String color;

// Default constructor (no arguments) with default values


public Circle() {
this.radius = 1.0;
this.color = "red";
}

// Constructor with radius and color as arguments


public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}

// Public method to get the radius


public double getRadius() {
return radius;
}

// Public method to calculate and return the area


public double getArea() {
return Math.PI * radius * radius;
}

// Optional: Method to get color


public String getColor() {
return color;
}

public static void main(String[] args) {


// Creating circle instances
Circle circle1 = new Circle(); // Default constructor
Circle circle2 = new Circle(5.0, "blue"); // Constructor with radius and color
// Displaying results
System.out.println("Circle 1 -> Radius: " + circle1.getRadius() + ", Area: " +
circle1.getArea() + ", Color: " + circle1.getColor());
System.out.println("Circle 2 -> Radius: " + circle2.getRadius() + ", Area: " +
circle2.getArea() + ", Color: " + circle2.getColor());
}
}

Features in This Implementation


Encapsulation: radius and color are private.
Constructors Overloading: Supports both default values and custom
initialization.
Getter Methods: getRadius() , getArea() , and getColor() for controlled access.
Mathematical Calculation: Computes area using math.

2. A class called rectangle is designed as following. It contains: Three private


instance variables: length & breath (of the type double) and color (of the type
String), with default value of 5.0 & 7.0 and "red", respectively. Two overloaded
constructors - a default constructor with no argument, and a constructor which
takes a double argument for radius and color. Two public methods:
getLengthBreath(), getPerimeter(), getColor(), and getArea(), which return the
length breath, perimeter, color and area of this instance, respectively.

package sample1;
public class Rectangle {
// Private instance variables
private double length;
private double width;
private String color;

// Default constructor (no arguments) with default values


public Rectangle() {
this.length = 1.0;
this.width = 1.0;
this.color = "red";
}

// Constructor with length and width


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
this.color = "red"; // Default color
}

// Constructor with length, width, and color


public Rectangle(double length, double width, String color) {
this.length = length;
this.width = width;
this.color = color;
}

// Public method to get length


public double getLength() {
return length;
}

// Public method to get width


public double getWidth() {
return width;
}

// Public method to get color


public String getColor() {
return color;
}

// Method to calculate and return area


public double getArea() {
return length * width;
}

// Method to calculate and return perimeter


public double getPerimeter() {
return 2 * (length + width);
}

public static void main(String[] args) {


// Creating rectangle instances
Rectangle rect1 = new Rectangle(); // Default constructor
Rectangle rect2 = new Rectangle(5.0, 3.0, "blue"); // Constructor with values
// Displaying results
System.out.println("Rectangle 1 -> Length: " + rect1.getLength() + ", Width: " +
rect1.getWidth() +
", Area: " + rect1.getArea() + ", Perimeter: " + rect1.getPerimeter() +
", Color: " + rect1.getColor());

System.out.println("Rectangle 2 -> Length: " + rect2.getLength() + ", Width: " +


rect2.getWidth() +
", Area: " + rect2.getArea() + ", Perimeter: " + rect2.getPerimeter() +
", Color: " + rect2.getColor());
}
}
Features in this program
Encapsulation: length, breath, perimeter and color are private.
Constructors Overloading: Supports both default values and custom
initialization.
Getter Methods: getLengthBreath() , getPerimeter(), getArea() , and getColor()
for controlled access.
Mathematical Calculation: Computes area using math.

3. Abstract Superclass Shape and Its Concrete Subclasses. The superclass Shape
and its subclasses Circle, Rectangle and Square are as follows. Shape is an
abstract class containing 2 abstract methods: getArea() and getPerimeter(), where
its concrete subclasses must provide its implementation. All instance variables
shall have protected access, i.e., accessible by its subclasses and classes in the
same package. Mark all the overridden methods with annotation @Override.

package sample1;
// Abstract superclass Shape
abstract class Shape {
protected String color; // Protected instance variable

// Constructor for Shape


public Shape(String color) {
this.color = color;
}

// Abstract methods (must be implemented by subclasses)


public abstract double getArea();
public abstract double getPerimeter();

// Getter method for color


public String getColor() {
return color;
}
}

// Concrete subclass Circle


class Circle extends Shape {
protected double radius;

// Constructor
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}

// Implement getArea() method


@Override
public double getArea() {
return Math.PI * radius * radius;
}

// Implement getPerimeter() method


@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}

// Concrete subclass Rectangle


class Rectangle extends Shape {
protected double length, width;

// Constructor
public Rectangle(double length, double width, String color) {
super(color);
this.length = length;
this.width = width;
}

// Implement getArea() method


@Override
public double getArea() {
return length * width;
}

// Implement getPerimeter() method


@Override
public double getPerimeter() {
return 2 * (length + width);
}
}

// Concrete subclass Square (inherits from Rectangle)


class Square extends Rectangle {
// Constructor
public Square(double side, String color) {
super(side, side, color); // Square has equal sides
}
}

public class ShapeDemo {


public static void main(String[] args) {
// Creating instances of each shape
Shape circle = new Circle(5.0, "Blue");
Shape rectangle = new Rectangle(4.0, 6.0, "Green");
Shape square = new Square(4.0, "Red");

// Displaying results
System.out.println("Circle - Color: " + circle.getColor() + ", Area: " +
circle.getArea() + ", Perimeter: " + circle.getPerimeter());
System.out.println("Rectangle - Color: " + rectangle.getColor() + ", Area: " +
rectangle.getArea() + ", Perimeter: " + rectangle.getPerimeter());
System.out.println("Square - Color: " + square.getColor() + ", Area: " +
square.getArea() + ", Perimeter: " + square.getPerimeter());
}
}

Key Features
Abstract Class () →(Shape Contains → getArea() and getPerimeter() abstract
methods.
Protected Variables → Allows access within subclasses.
Overridden Methods () → Concrete subclasses implement and .
Square Extends Rectangle → A square is a special case of a rectangle.

4. Abstract Superclass Shape and Its Concrete Subclasses. How would you design
the vehicle superclass and ensure its subclasses (car, bike, and truck ) implement
getMaxSpeed() and getFuelEfficiency() properly? All instance variables shall have
protected access, i.e., accessible by its subclasses and classes in the same
package. Mark all the overridden methods with annotation @Override.

// Abstract superclass Vehicle


abstract class Vehicle {
protected int speed; // Protected instance variable for speed
protected double fuelEfficiency; // Protected variable for fuel efficiency (km/l)

// Constructor
public Vehicle(int speed, double fuelEfficiency) {
this.speed = speed;
this.fuelEfficiency = fuelEfficiency;
}

// Abstract methods (must be implemented by subclasses)


public abstract int getMaxSpeed();
public abstract double getFuelEfficiency();

// Getter for speed


public int getSpeed() {
return speed;
}
}

// Concrete subclass Car


class Car extends Vehicle {
// Constructor
public Car(int speed, double fuelEfficiency) {
super(speed, fuelEfficiency);
}

// Implement getMaxSpeed()
@Override
public int getMaxSpeed() {
return speed;
}

// Implement getFuelEfficiency()
@Override
public double getFuelEfficiency() {
return fuelEfficiency;
}
}

// Concrete subclass Bike


class Bike extends Vehicle {
// Constructor
public Bike(int speed, double fuelEfficiency) {
super(speed, fuelEfficiency);
}

// Implement getMaxSpeed()
@Override
public int getMaxSpeed() {
return speed;
}

// Implement getFuelEfficiency()
@Override
public double getFuelEfficiency() {
return fuelEfficiency;
}
}

// Concrete subclass Truck


class Truck extends Vehicle {
// Constructor
public Truck(int speed, double fuelEfficiency) {
super(speed, fuelEfficiency);
}

// Implement getMaxSpeed()
@Override
public int getMaxSpeed() {
return speed;
}

// Implement getFuelEfficiency()
@Override
public double getFuelEfficiency() {
return fuelEfficiency;
}
}

public class VehicleDemo {


public static void main(String[] args) {
// Creating instances of each vehicle type
Vehicle car = new Car(180, 15.0);
Vehicle bike = new Bike(120, 40.0);
Vehicle truck = new Truck(100, 8.0);

// Displaying results
System.out.println("Car - Max Speed: " + car.getMaxSpeed() + " km/h, Fuel
Efficiency: " + car.getFuelEfficiency() + " km/l");
System.out.println("Bike - Max Speed: " + bike.getMaxSpeed() + " km/h, Fuel
Efficiency: " + bike.getFuelEfficiency() + " km/l");
System.out.println("Truck - Max Speed: " + truck.getMaxSpeed() + " km/h, Fuel
Efficiency: " + truck.getFuelEfficiency() + " km/l");
}
}

You might also like