Question 1: Primitive Types vs Reference Types (Unit 1)

MCQ Question

public class Person {
    String name;
    int age;
    int height;
    String job;

    public Person(String name, int age, int height, String job) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.job = job;
    }
}

public static void main(String[] args) {
    Person person1 = new Person("Carl", 25, 165, "Construction Worker");
    Person person2 = new Person("Adam", 29, 160, "Truck Driver");
    Person person3 = person1;
    int number = 16;
    System.out.println(number);
}
main(null);

Answer the following questions based on the code above:

a. What kind of types are person1 and person2? Answer: reference types b. Do person1 and person3 point to the same value in memory? Answer: yes c. Is the integer “number” stored in the heap or in the stack? Answer: stack d. Is the value that “person1” points to stored in the heap or in the stack? Answer: heap

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 a form of data types in Java that hold their values directly in memory, not a reference to the data. Example of primitive types include int, char, boolean, double, and long (not limited to this list). More specific examples could include int age = 16, double salary = 5000.75, and char whatever = S

Reference types, on the other hand, are form of data types in Java that, as the name suggests, stores a reference to the actual data and not the data itself. They allow us to be able to access objects stored elsewhere in memory. Examples of reference types in Java include class, Arrays, and String.

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

Whereas primitive types store a reference to the data in memory, primitive types store the actual data held by the variable. While reference types have an unlimited number defined by the user, primitive types are limited in number and are predefined in the language. Whereas memory for primitive types is allocated temporarily on the stack, objects of reference type variables are stored on 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.

class Customer {
    private String name; // reference type for the customer's name
    private double interestRate; // primitive type used for the interest rate


    // constructor with both a reference type (String) and primitive type (double) as parameters
    public Customer(String name, double interestRate) {
        this.name = name; // assigns reference type variable
        this.interestRate = interestRate; // assigns primitive type variable
    }

    public double getInterestRate() {
        return interestRate; // primitive type variable returned
    }

    public String getName() {
        return name; // reference type variable returned
    }
}

public class BankingApplication {

    public double calculateInterest(double principal, Customer customer) {
        // gets the interest rate from the Customer object
        double interestRate = customer.getInterestRate();
        
        // Calculate the interest amount using the principal and the customer-specific interest rate
        double interest = principal * interestRate; 
        
        // Returns the calculated interest
        return interest;
    }

    public static void main(String[] args) { // test case


        Customer customer = new Customer("John Doe", 0.05); // 5% interest rate
        
        // instance of the BankingApplication
        BankingApplication app = new BankingApplication();
        
        // interest for a given principal amount
        double principal = 1000; // Principal amount
        double interest = app.calculateInterest(principal, customer);
        
        // Print the calculated interest
        System.out.println("Interest: $" + interest);
    }

}

BankingApplication.main(null);
Interest: $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 going through through the array row by row or column by column to access each element. Since a 2D array is an array of arrays, there are usually two nested loops: the outer loop iterates over the rows (or the first dimension), and the inner loop iterates over the columns (or the second dimension) of each row.

One example where iterating over a 2D array is useful is in a game development setting, especially with grid-based games (ex. chess, tic-tac-toe, or minesweeper). Here, the rows and columns correspond to the board’s grid, and each element stores information about that cell (like whether or not there is a mine in minesweeper or whether a cell is empty, contains an ‘X’, or an ‘O’ in tic-tac-toe). Iterating over a 2D array in games like these allows us to check the state of the game, update the board, or calculate scores based on the position of pieces or marks.

(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.

Note For Question 3

The Google Doc and the blog with all the FRQs had different things for question 3. Whereas the Google Doc said to define an ArrayList and its significance with an ArrayList code segment, the blog said to do all of that but with an Array. Just to be safe, I answered question 3 for both Arrays and ArrayLists.

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 container object that holds a fixed (immutable) number of values of a single type. The length of an array is established when the array is created and cannot be changed once created (values cannot be added or removed to the array). Each item in an array is called an element, and each element is accessed by its numerical index. Arrays in Java are zero-based, meaning the first element’s index is 0. Arrays are significant in that they provide a simple way to group and manage collections of similar data types, making updating and accessing data easy since their size is fixed.

(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 StudentManagementSystem { // array version

    
    public static double calculateAverageGrade(int[] grades) {
        if (grades.length == 0) return 0.0; // Return 0 if the array is empty to avoid division by zero
        
        double sum = 0; // Initialize the sum of grades
        // Iterate over each grade in the array
        for (int grade : grades) {
            sum += grade; // Add each grade to the sum
        }
        
        // Calculate the average by dividing the sum by the number of grades
        return sum / grades.length;
    }

    public static void main(String[] args) {
        int[] gradesArray = {80, 90, 75, 85};
        double averageArray = calculateAverageGrade(gradesArray);
        System.out.println("Average Grade (Array): " + averageArray);

    }
}

StudentManagementSystem.main(null); /* */
Average Grade (Array): 82.5

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 part of the java.util package and is a mutable array implementation of the List interface. Unlike arrays (Arrays) that have a fixed length (immutable), ArrayLists can dynamically adjust their size to accommodate adding or removing elements. This makes ArrayList particularly useful for scenarios where the number of elements can change over time (ex. number of people in a school club)

(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 StudentManagementSystem { // arraylist version

    public static double calculateAverageGrade(ArrayList<Integer> grades) {
        if (grades.isEmpty()) return 0.0; // Returns 0 if the list is empty
        
        double sum = 0; // Initialize sum of grades to 0
        // Iterates over each grade in the ArrayList
        for (int grade : grades) {
            sum += grade; // Add each grade to the sum
        }
        
        // Calculate average by dividing sum by the number of grades
        return sum / grades.size();
    }

    public static void main(String[] args) {
        ArrayList<Integer> gradesArrayList = new ArrayList<>();
        gradesArrayList.add(80);
        gradesArrayList.add(90);
        gradesArrayList.add(75);
        gradesArrayList.add(85);
        double averageArrayList = calculateAverageGrade(gradesArrayList);
        System.out.println("Average Grade (ArrayList): " + averageArrayList);

    }
}

StudentManagementSystem.main(null);/* */
Average Grade (ArrayList): 82.5

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.

The Math class in Java is part of the java.lang package, which is automatically imported, hence you don’t need to manually import it. The Math class provides a collection of methods and constants for performing mathematical operations.T he methods of the Math class are static, meaning you can call them directly using the class name without needing to create an instance of the Math class.

Commonly used math methods include..

  • Math.abs(double a): Returns the absolute value of a.
  • Math.sqrt(double a): Returns the square root of a.
  • Math.pow(double a, double b): Returns a raised to the power of b.
  • Math.max(double a, double b): Returns the greater of a and b.
  • Math.min(double a, double b): Returns the lesser of a and b.
  • Math.round(double a): Rounds a to the nearest integer.
  • Math.random(): Returns a double value greater than or equal to 0.0 and less than 1.0. (VERY IMPORTANT ONE TO KNOW FOR THE EXAM)

(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.

public class ScientificCalculator {

    public static double calculateSquareRoot(double number) {
        // Use Math.sqrt() method to calculate the square root of the double.
        double result = Math.sqrt(number);
        return result; // returns square root
    }

    public static void main(String[] args) {
        double number = 35;
        double squareRoot = calculateSquareRoot(number);
        System.out.println("Square Root: " + squareRoot);


    }

}

ScientificCalculator.main(null);

Square Root: 5.916079783099616

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.

The if statement in Java is used to execute a block of code based on a condition. If the condition is true, the block of code within the if statement is executed. Otherwise, it is skipped.

Example:

if (age >= 18) {
    System.out.println("You are eligible to vote!");
}

The while loop in Java is used to repeatedly execute a block of code as long as a given condition is true.

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

The else statement in Java is used along with an if statement and executes a block of code when the if statement’s condition is false.

if (score >= 60) {
    System.out.println("You passed.");
} else { // else statement
    System.out.println("You failed.");
}

(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.

public class GradingSystem {

    public static void printGradeStatus(int score) {
        // if statement to check if the score is 60 or above
        if (score >= 60) {
            System.out.println("You passed!"); // will print "You passed!" if the condition is true
        } else {
            System.out.println("You failed!"); // will print "You failed!" if the condition is false
        }
    }

    public static void main(String [] args){
        int score1 = 78;
        int score2 = 46;
        printGradeStatus(score1);
        printGradeStatus(score2);

    }
}

GradingSystem.main(null);
You passed!
You failed!