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 in Java are the basic data types provided by the language itself. They hold simple values and are not objects. Examples include int, double, boolean, char, etc.

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

Reference types, on the other hand, are complex data types that are defined by classes in Java. They hold references (memory addresses) to objects stored in the heap memory. Examples include objects of classes like String, ArrayList, Customer, etc. Primitive types are allocated memory on the stack, and their values are stored directly. Reference types are allocated memory on the heap, and variables of reference types hold references (memory addresses) to the actual objects stored in the heap. Primitive types are used for simple data storage and manipulation. Reference types are used to represent complex objects and enable more sophisticated behavior through methods and inheritance.

(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{
    
    public void calculateInterest(){

    }
}
public class BankingApplication {
    
    // Customer class representing customer information
    public class Customer {
        private String name;
        private int age;
        private double interestRate; // Assuming this is the interest rate associated with the customer

        // Constructor for Customer Class
        public Customer(String name, int age, double interestRate) {
            this.name = name;
            this.age = age;
            this.interestRate = interestRate;
        }

        // Getter for interest rate
        public double getInterestRate() {
            return interestRate;
        }
    }

    // Method signature
    public void calculateInterest(double principal, Customer customer) {
        // Method implementation
        // Perform calculations based on principal and customer information
        double interestRate = customer.getInterestRate();
        double interest = principal * interestRate;

        // Display the calculated interest
        System.out.println("Interest calculated: " + interest);
    }

    // Main method for testing
    public static void main(String[] args) {
        // Create an instance of BankingApplication
        BankingApplication bankingApp = new BankingApplication();

        // Create a Customer object
        Customer customer = bankingApp.new Customer("John Doe", 35, 0.05); // Example values for name, age, and interest rate

        // Call the calculateInterest method
        bankingApp.calculateInterest(1000.0, customer); // Example principal amount
    }
}
BankingApplication.main(null);

Interest calculated: 50.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 in Java involves traversing through each element of the array, row by row and column by column, to perform certain operations or access the values stored in the array. This process involves nested loops, where one loop iterates over the rows and another loop iterates over the columns.

Example scenario: Suppose you are developing a program to calculate the average score of students in a classroom where each student has taken multiple exams. You store the scores in a 2D array where each row represents a student, and each column represents an exam. Iterating over this 2D array allows you to access each individual score and calculate the average score for each student or the average score for each exam across all students. This iteration is useful for statistical analysis or generating reports based on the exam scores.

(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
    public int calculateTotalScore(int[][] scores) {
        int totalScore = 0; // Initialize total score variable to store the sum

        // Iterate over the 2D array to calculate the total score
        for (int i = 0; i < scores.length; i++) {
            for (int j = 0; j < scores[i].length; j++) {
                totalScore += scores[i][j]; // Add each element to the total score
            }
        }

        return totalScore; // Return the calculated total score
    }

    // Main method for testing
    public static void main(String[] args) {
        // Example 2D array of scores
        int[][] scores = {
            {10, 20, 30},
            {15, 25, 35},
            {5, 10, 15}
        };

        // Create an instance of ScoreCalculator
        ScoreCalculator calculator = new ScoreCalculator();

        // Call the calculateTotalScore method and print the result
        int totalScore = calculator.calculateTotalScore(scores);
        System.out.println("Total score: " + totalScore);
    }
}

ScoreCalculator.main(null);

Total score: 165

Question 3: ArrayList (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 arrayList in Java. Explain its significance and usefulness in programming.

An ArrayList in Java is a dynamic array-like data structure provided by the Java Collections Framework. It implements the List interface and provides resizable arrays, which means the size of the ArrayList can be dynamically adjusted as elements are added or removed. Unlike regular arrays, ArrayLists can grow or shrink automatically to accommodate the changing number of elements.

(b) Code:

You need to implement a method calculateAverageGrade that takes an arrayList grades of integers representing student grades and returns the average of all the elements in the arrayList. Write the method signature and the method implementation. Include comments to explain your code.

import java.util.ArrayList;

public class GradeCalculator {

    // Method signature
    public double calculateAverageGrade(ArrayList<Integer> grades) {
        if (grades.isEmpty()) {
            return 0.0; // Return 0 if the ArrayList is empty to avoid division by zero
        }

        int sum = 0; // Initialize sum variable to store the total sum of grades

        // Iterate over the ArrayList to calculate the sum of grades
        for (int grade : grades) {
            sum += grade;
        }

        // Calculate the average grade
        double average = (double) sum / grades.size();

        return average; // Return the calculated average
    }

    // Main method for testing
    public static void main(String[] args) {
        // Example ArrayList of grades
        ArrayList<Integer> grades = new ArrayList<>();
        grades.add(80);
        grades.add(90);
        grades.add(75);
        grades.add(85);

        // Create an instance of GradeCalculator
        GradeCalculator calculator = new GradeCalculator();

        // Call the calculateAverageGrade method and print the result
        double averageGrade = calculator.calculateAverageGrade(grades);
        System.out.println("Average grade: " + averageGrade);
    }
}

GradeCalculator.main(null);
Average grade: 82.5
// Parent class
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

// Child class inheriting from the Animal class
class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
        super.sound();
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of Dog
        Dog myDog = new Dog();

        // Calling the sound method of Dog class
        myDog.sound(); // Output: Dog barks
        // Since Dog class extends Animal class, it can also access methods from Animal class
        // Calling the sound method of Animal class using 'super'
    }
}
Main.main(null);

Dog barks
Animal makes a sound