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 are basic data types in Java and are used to store simple values
    • Examples: int, double, boolean, char
      int age = 17;
      
  • Reference types are non-primitive types that store references to objects
    • Examples: classes, arrays, strings, interfaces
      String name = "Kaiden";
      

      (b) Explain the differences between primitive types and reference types in terms of memory allocation and usage in Java programs.

  • The primitive and reference types are different because the primitive types store the actual values, while the reference types store a reference to where the data is located. For the primitive type, the space is allocated for the actual value when the variable is created, but for the reference variable, the space is allocated for the reference. Primitive types store the actual value, so the operations with them are quick and easy, but reference types are a bit slower because the operations access the object through the reference.

(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 Customer {
    private String name;
    private int creditScore;
    // Constructor to initialize name and credit score
    public Customer(String name, int creditScore) {
        this.name = name;
        this.creditScore = creditScore;
    }
    // getter method for name
    public String getName() {
        return name;
    }
    // setter method for name
    public void setName(String name) {
        this.name = name;
    }



    //getter method for credit score
    public int getCreditScore() {
        return creditScore;
    }
    //Setter method for credit score
    public void setCreditScore(int creditScore) {
        this.creditScore = creditScore;
    }
}
public class Test {
    public static void main(String[] args) {
        double principal = 50000;
        System.out.println("Principal: "+principal+", Interest rate: 0.05");
        Customer customer = new Customer("Kaiden", 700);
        double interest = calculateInterest(principal, customer);
        System.out.println(customer.getName()+ " - Credit Score: "+ customer.getCreditScore()+", Interest: "+interest);
    }
    // Method signature for calculateInterest
    // Takes a primitive double for principal amount and a reference type Customer for customer information
    public static double calculateInterest(double principal, Customer customer) {
        // Calculate interest based on principal and customer credit score
        // For example, let's say the interest rate is 5%
        double interestRate = 0.05;
        double interest = principal * interestRate;
        // Print customer name, credit score, and total interest
        System.out.println("Customer Name: " + customer.getName());
        System.out.println("Customer Credit Score: " + customer.getCreditScore());
        System.out.println("Total Interest: " + interest);
        // Return the total interest
        return interest;
    }
}
Test.main(null);
Principal: 50000.0, Interest rate: 0.05
Customer Name: Kaiden
Customer Credit Score: 700
Total Interest: 2500.0
Kaiden - Credit Score: 700, Interest: 2500.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.

Iterating over a 2D in Java uses nested for loops usually to iterate through each element in the 2D array, the outer loop usually does the rows and the inner loop does the columns. Iterating over a 2D array is useful in the game because you could make the row the different levels and the columns as the scores for the attempts. By iterating over the 2D array, you can sum up all the scores to calculate the top score for the levels or the average scores for each level.

(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 Game {
    private int[][] scores;
    // this is the constructor to initialize the 2D array of scores
    public Game(int[][] scores) {
        this.scores = scores;
    }
    //calculates total score from a 2D array of player scores
    public int calculateTotalScore() {
        int totalScore = 0;
        // iterates over each element in the 2D array
        for (int i = 0; i < scores.length; i++) {
            for (int j = 0; j < scores[i].length; j++) {
                //adds score to the total score
                totalScore += scores[i][j];
            }
        }
        //returns the total score
        return totalScore;
    }
    public static void main(String[] args) {
        //2D array of player scores
        int[][] playerScores = {
                {10, 20, 30},
                {15, 50, 5},
                {5, 40, 0}
        };
        Game game = new Game(playerScores);
        int totalScore = game.calculateTotalScore();
        System.out.println("Total Score: " + totalScore);
    }
}
Game.main(null);
Total Score: 175

Arrays Hacks (a) Definition and Significance of Arrays in Java An array in Java is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created and cannot be changed after creation. Each item in an array is called an element, and each element is accessed by its numerical index, with the first element being at index 0.

Significance and Usefulness: Arrays are fundamental data structures in programming, used to store collections of data. They are particularly useful when there is a need to organize data for easy access by a numeric index. Here are some key points that highlight the significance of arrays:

Efficiency: Arrays are stored in contiguous memory locations, which makes accessing elements by their index very efficient. Simplicity: Arrays provide a straightforward way to implement and manage collections of variables of the same type. Use Cases: Arrays are used in a wide range of applications, from simple data storage to being the building blocks for more complex data structures. They are especially useful in scenarios where the number of elements is known beforehand, and elements need to be quickly accessed by index. Looping: Arrays can be easily iterated over using loops, making them ideal for processing collections of data. (b) Code: calculateAverageGrade Method Here is how the calculateAverageGrade method can be implemented. This method calculates the average grade from an array of integers representing student grades.

public class StudentManagementSystem {
    
    /**
     * Calculates the average grade for an array of grades.
     * 
     * @param grades An array of integers representing student grades.
     * @return The average grade as a double.
     */
    public static double calculateAverageGrade(int[] grades) {
        if (grades == null || grades.length == 0) {
            // Return 0.0 if the grades array is null or empty.
            return 0.0;
        }
        
        double sum = 0; // Initialize sum of all grades to 0.
        
        // Iterate over each grade in the array and add it to the sum.
        for (int grade : grades) {
            sum += grade;
        }
        
        // Calculate the average by dividing the total sum by the number of grades.
        double average = sum / grades.length;
        
        // Return the calculated average.
        return average;
    }
    
    // Example usage
    public static void main(String[] args) {
        int[] studentGrades = {90, 85, 92, 78, 65, 88}; // Example array of grades
        double averageGrade = calculateAverageGrade(studentGrades);
        
        System.out.println("Average Grade: " + averageGrade);
    }
}

StudentManagementSystem.main(null); Average Grade: 83.0 Explanation:

The calculateAverageGrade method takes an array of integers grades as its parameter. The method first checks if the grades array is null or empty (grades.length == 0) and returns 0.0 in such cases to avoid division by zero or processing an invalid array. It then iterates over each grade in the array, adding each grade to a cumulative sum. After iterating through all grades, the method calculates the average by dividing the total sum by the number of grades in the array. The calculated average is returned as a double. This ensures that the average is precise even when the division result is not a whole number.