Question 1: Primitive Types vs Reference Types (Unit 1)
Situation: You are developing a banking application where you need to represent customer information. You have decided to use both primitive types and reference types for this purpose.
(a) Define primitive types and reference types in Java. Provide examples of each.
- Primitive types represent basic data types in Java and are predefined by the language. They are not objects and do not have methods associated with them. They are stored directly in memory, and their values are accessed quickly.
int num = 10; double pi = 3.14; char letter = 'A'; boolean flag = true;
- Reference types refer to objects in memory. They are created using classes or interfaces and store references (memory addresses) to objects. Reference types can have methods and other members associated with them. They are allocated memory in the heap.
String str = "Hello"; // String is a reference type MyClass obj = new MyClass(); // MyClass is a class defined elsewhere int[] array = new int[5]; // array is a reference type
(b) Explain the differences between primitive types and reference types in terms of memory allocation and usage in Java programs.
- Primitive types store their values in memory and reference types store references to values in the heap. Primitive types have a limited memory size that depends on the type while reference variable are stored in the stack memory, while the object’s data is stored in the heap.
(c) Code:
You have a method calculateInterest
that takes a primitive double
type representing the principal amount and a reference type Customer
representing the customer information. Write the method signature and the method implementation. Include comments to explain your code.
public class BankingApplication {
// this is the customer class used in the calculateInterest method
public static class Customer {
private String name; // refrence type
public Customer(String name) {
this.name = name;
}
}
// method signature for calculating interest
public static double calculateInterest(double principalAmount, Customer customer) {
double interestRate = 0.05; // 5% primitive type
double interest = principalAmount * interestRate; // primitive type
return interest;
}
public static void main(String[] args) {
Customer customer = new Customer("Soham Kamat");
double principalAmount = 1000.00;
double interest = calculateInterest(principalAmount, customer);
System.out.println("Interest: $" + interest);
System.out.println("Total: $" + (interest + principalAmount));
}
}
BankingApplication.main(null);
Interest: $50.0
Total: $1050.0
Question 2: Iteration over 2D arrays (Unit 4)
Situation: You are developing a game where you need to track player scores on a 2D grid representing levels and attempts.
(a) Explain the concept of iteration over a 2D array in Java. Provide an example scenario where iterating over a 2D array is useful in a programming task.
- Iteration over a 2D array means going through each element in the array. In a 2D Array, this is most commonly done with a nested for loop. One is used for iterating through the rows and the other is used for iterating through the columns. Iterating over a 2D array is useful when you are
(b) Code:
You need to implement a method calculateTotalScore that takes a 2D array scores of integers representing player scores and returns the sum of all the elements in the array. Write the method signature and the method implementation. Include comments to explain your code.
public class ScoreCalculator {
// method signature for calculating total score
public static int calculateTotalScore(int[][] scores) {
int totalScore = 0; // primitive type
// Iterate through each row of the 2D array
for (int i = 0; i < scores.length; i++) {
// Iterate through each element in the current row
for (int j = 0; j < scores[i].length; j++) {
// Add the current element to the total score
totalScore += scores[i][j];
}
}
// Return the total score
return totalScore;
}
public static void main(String[] args) {
int[][] playerScores = { // refrence type
{10, 20, 30}, // Sum: 60
{5, 15, 25}, // Sum: 45
{8, 16, 24} // Sum: 48
}; // Total Sum: 153
// Calculate total score
int totalScore = calculateTotalScore(playerScores);
// Print total score
System.out.println("Total Score: " + totalScore);
}
}
ScoreCalculator.main(null);
Total Score: 153
Question 3: Array (Unit 6)
Situation: You are developing a student management system where you need to store and analyze the grades of students in a class.
(a) Define an array in Java. Explain its significance and usefulness in programming.
- An array in Java is a data structure that stores a fixed-size collection of elements of the same type. It has the ability to efficiently store and access multiple elements of data sequentially, allowing for easy manipulation and processing of data in algorithms and programs.
(b) Code:
You need to implement a method calculateAverageGrade that takes an array grades of integers representing student grades and returns the average of all the elements in the array. Write the method signature and the method implementation. Include comments to explain your code.
public class GradeAnalyzer {
// method signature for calculating average grade
public static double calculateAverageGrade(int[] grades) {
int sum = 0; // primitive type
// Iterate through each element in the array
for (int grade : grades) {
// Add the current grade to the sum
sum += grade;
}
// calculate the average
double average = (double) sum / grades.length; // primitive type
return average;
}
public static void main(String[] args) {
int[] studentGrades = {85, 90, 75, 88, 92}; // refrence type
// Calculate average grade
double averageGrade = calculateAverageGrade(studentGrades);
// Print average grade
System.out.println("Average Grade: " + averageGrade);
}
}
GradeAnalyzer.main(null);
Average Grade: 86.0
Question 4: Math Class (Unit 2)
Situation: You are developing a scientific calculator application where users need to perform various mathematical operations.
(a) Discuss the purpose and utility of the Math class in Java programming. Provide examples of at least three methods provided by the Math class and explain their usage.
(b) Code:
You need to implement a method calculateSquareRoot that takes a double number as input and returns its square root using the Math class. Write the method signature and the method implementation. Include comments to explain your code.
Question 5: If, While, Else (Unit 3-4)
Situation: You are developing a simple grading system where you need to determine if a given score is passing or failing.
(a) Explain the roles and usage of the if statement, while loop, and else statement in Java programming. Provide examples illustrating each.
(b) Code:
You need to implement a method printGradeStatus that takes an integer score as input and prints “Pass” if the score is greater than or equal to 60, and “Fail” otherwise. Write the method signature and the method implementation. Include comments to explain your code.