Question 1: Primitive Types vs Reference Types (Unit 1)
MCQ Question
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 data types are the most base level data type (can’t be divided further into smaller data types). They come as part if the Java language, but can be manipulated. An example of a primitive data type is a boolean
Reference data types are any non-primitive data type. They are not pre-defined, but have to be created by the programmer. Reference data types are not stored in the program itself, but instead using a reference data type creates a connection (reference) to a different memory location which stores that information. AN example of a reference type is a class
(b) Explain the differences between primitive types and reference types in terms of memory allocation and usage in Java programs.
Primitive types are stored in the program itself. They values they store can’t be changed once they are defined (though the variable can be reassigned to a new value)
Reference types are not stored in the program. Instead, we store the reference to a different location, which holds the information we need. Using a reference type means you are accessing that memory location
(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 InterestSim {
public static class Customer { // creating customer class so we can create object
private String name;
private int creditScore;
public Customer(String name, int creditScore) {
this.name = name;
this.creditScore = creditScore;
}
public int getCreditScore() {
return creditScore;
}
}
public static double calculateInterest(double principalAmount, Customer customer) { //interestRate is a PRIMITIVE TYPE (double); Customer is a REFERNCE TYPE (class)
double interestRate = 0.0; // initializing interest rate --> changes based on credit score
int creditScore = customer.getCreditScore(); //credit score is attribute of Customer
if (creditScore >= 300 && creditScore <= 579) { // interest rate changes based on credit score
interestRate = 0.05;
} else if (creditScore >= 580 && creditScore <= 669) {
interestRate = 0.1;
} else if (creditScore >= 670 && creditScore <= 799) {
interestRate = 0.15;
} else if (creditScore >= 800 && creditScore <= 850) {
interestRate = 0.2;
}
return principalAmount * interestRate;
}
public static void main(String[] args) {
Customer customer = new Customer("John Mortensen", 700);
double principalAmount = 10000; // principal amount $10,000
double interest = calculateInterest(principalAmount, customer);
System.out.println("Interest calculated: " + interest);
}
}
interestSim.main(null);
Interest calculated: 1500.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.
To iterate over a 2D array, we would need to access every element. That means we have to first iterate through each row one by one, and within each row we have to iterate through the columns. To do this, nested for loops are used.
Iteration through 2D arrays are very commonly used for images, since pixels already come in a 2D array. Accessing the information of each pixel in an image (RGB values) would require a 2D iteration, using the pixels row and column values.
(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 CalculatingScores {
public int calculateTotalScore(int[][] scores) { //method takes 2d array of scores
int totalScore = 0; // total score var intilalizing
//2d iteration
for (int i = 0; i < scores.length; i++) { //iterating through each row
for (int j = 0; j < scores[i].length; j++) { //iterating through each column
totalScore += scores[i][j];
}
}
return totalScore;
}
public static void main(String[] args) {
int[][] scores = {{15, 24, 78, 29},
{90, 67, 37, 65},
{42, 55, 75, 93}};
CalculatingScores calculator = new CalculatingScores();
int totalScore = calculator.calculateTotalScore(scores);
System.out.println("total Score: " + totalScore);
}
}
CalculatingScores.main(null);
total Score: 670
Question 3 – taught by my team
Question 4
Situation: You are developing a scientific MathClass 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 purpose of the Math class is to provide more functionality for math. It allows you to more easily do common math operations, which would have required more code to accomplish with just plain Java.
Three methods:
- Math.toRadians(double angdeg) : takes in a double that is a degree value, converts it into radians
- Math.round(float a) : rounds into an integer following basic rounding rules
- Math.cos(double a) : returns the cosine of an angle value
(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 SquareRootCalculator {
public static double calculateSquareRoot(double input) { //takes in double number as input
double squareRoot = Math.sqrt(input); //finding squareRoot
return squareRoot;
}
public static void main(String[] args) {
double input = 38.3;
double squareRoot = calculateSquareRoot(input);
System.out.println(squareRoot);
}
}
SquareRootCalculator.main(null)
6.18869937870632
Question 5
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.
IF STATEMENT/ELSE STATEMENT: allows the program to make a decision based on conditions created by programmer. Different code is run based on the condition that is met. The else statement gives the program other instructions for if the condition is not met. m
An example would be the following code snippet
int n = 10;
boolean bool;
if (n > 20) { //if this condition is true
bool = true; // do this
} else { // if the condition was not met
bool = false; // do this
};
System.out.println(bool);
OUTPUT: the condition was not met so bool is false
WHILE LOOP: while something is true, the code within the while loop continues to run. This is more flexible than if statements because it automatically repeats until condition is met.
int count = 0;
while (count < 5) { //while loop will run while count is less than 5
count++;
}
System.out.println("count is over"); // this runs when while loop is over
(b) 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 GradeChecking {
public static void printGradeStatus(int score) { //takes an integer score
if (score >= 60) { // if the score is larger than 60, the program outputs PASS
System.out.println("pass");
}
else { // if the score is not larger than 60, the program outputs FAIL
System.out.println("fail");
}
}
public static void main(String[] args) {
printGradeStatus(75);
printGradeStatus(45);
}
}
GradeChecking.main(null);
pass
fail