Primitive Types vs Reference Types
Answers:
a) Both person1 and person2 are references to objects of type Person.
b) Yes, person1 and person3 point to the same value in memory. When you assign person1 to person3 (Person person3 = person1;
), you’re not creating a new object, but rather making person3 refer to the same object as person1.
c) The integer “number” is stored in the stack. Primitive types like integers are typically stored in the stack memory.
d) The value that “person1” points to (an instance of the Person class) is stored in the heap. Objects in Java are stored in the heap memory. So, person1 stores a reference to the actual object in the heap where the data for that person is stored.
(a) Primitive Types vs Reference Types in Java:
- Primitive Types: These are basic data types provided by Java, which are used to store simple values. Primitive types are not objects and are predefined by the language. They include
int
,double
,boolean
,char
, etc. Examples:
int num = 10;
double price = 20.5;
boolean isValid = true;
char grade = 'A';
- Reference Types: Reference types refer to objects in Java. They store references (memory addresses) to objects rather than the actual objects themselves. Examples of reference types include classes, interfaces, arrays, etc. Examples:
String name = "John Doe";
Customer customer = new Customer();
ArrayList<Integer> numbers = new ArrayList<>();
(b) Differences between Primitive Types and Reference Types:
- Memory Allocation:
- Primitive Types: Primitive types are allocated memory on the stack. The actual value is stored directly in memory.
- Reference Types: Reference types are allocated memory on the heap. The reference variable itself is stored on the stack, while the actual object is stored in the heap.
- Usage:
- Primitive Types: Primitive types hold the actual value. Operations performed on primitive types directly manipulate their values.
- Reference Types: Reference types hold references to objects. Operations performed on reference types often involve accessing and modifying the object’s properties or calling its methods indirectly through the reference.
(c) Method Signature and Implementation:
public class BankApplication {
// Method to calculate interest
// Takes a primitive double representing principal amount
// and a reference type Customer representing customer information
public double calculateInterest(double principalAmount, Customer customer) {
// Example implementation: calculate interest based on customer type
double interestRate;
if (customer.getType() == CustomerType.REGULAR) {
interestRate = 0.05; // Regular customer interest rate
} else {
interestRate = 0.07; // Premium customer interest rate
}
return principalAmount * interestRate;
}
// Customer class for reference type example
static class Customer {
private String name;
private CustomerType type;
// Constructor
public Customer(String name, CustomerType type) {
this.name = name;
this.type = type;
}
// Getter for customer type
public CustomerType getType() {
return type;
}
}
// Enum for customer type
enum CustomerType {
REGULAR,
PREMIUM
}
// Example usage
public static void main(String[] args) {
BankApplication bankApp = new BankApplication();
Customer customer1 = new Customer("John Doe", CustomerType.REGULAR);
double principalAmount = 1000.0;
double interest = bankApp.calculateInterest(principalAmount, customer1);
System.out.println("Interest for " + customer1.getName() + ": $" + interest);
}
}
calculateInterest
method takes a primitivedouble
for principal amount and a reference typeCustomer
.- It calculates interest based on customer type and returns it.
- The
Customer
class is a reference type representing customer information. - The
main
method demonstrates how to use thecalculateInterest
method with aCustomer
object.
Math Class
Scientific Calculator
(a) Purpose and Utility of the Math Class in Java Programming
The Math
class in Java provides a set of methods for performing common mathematical operations. It serves as a utility class for mathematical computations, offering functions for basic arithmetic, trigonometry, exponential, logarithmic, and rounding operations. Here are examples of three methods provided by the Math
class:
Math.abs(double a)
: This method returns the absolute value of a given number. It disregards the sign of the number and returns its positive equivalent. For example:double number = -10.5; double absValue = Math.abs(number); // absValue will be 10.5
Math.pow(double base, double exponent)
: This method returns the value of the first argument raised to the power of the second argument. It’s used for exponentiation. For example:double base = 2.0; double exponent = 3.0; double result = Math.pow(base, exponent); // result will be 8.0 (2^3)
Math.sin(double a)
: This method returns the sine of a given angle in radians. It’s useful for trigonometric calculations. For example:double angleInRadians = Math.PI / 6; // 30 degrees in radians double sinValue = Math.sin(angleInRadians); // sinValue will be 0.5
(b) Method Implementation: calculateSquareRoot
/**
* Calculates the square root of a given double number using the Math class.
*
* @param number The input number whose square root needs to be calculated.
* @return The square root of the input number.
*/
public static double calculateSquareRoot(double number) {
// Using Math.sqrt() to calculate the square root
double squareRoot = Math.sqrt(number);
return squareRoot;
}
Explanation:
- The method
calculateSquareRoot
takes adouble
parameternumber
for which the square root needs to be calculated. - Inside the method,
Math.sqrt()
is used to compute the square root of the input number. - The calculated square root is returned as the result of the method.
Array
(a) Iterating over a 2D array in Java involves using nested loops, typically one loop for the rows and another loop for the columns. This allows you to access each element of the array systematically.
A scenario where iterating over a 2D array is useful could be in a game where you need to keep track of player scores on different levels and attempts. You might represent this information using a 2D array, where each row represents a level and each column represents an attempt. Iterating over this array could help you calculate total scores, find maximum scores, or perform other operations on the scores data.
(b)
public class ScoreCalculator {
// Method to calculate total score from a 2D array
public static int calculateTotalScore(int[][] scores) {
// Variable to store total score
int totalScore = 0;
// Nested loops to iterate over each element in the 2D array
for (int row = 0; row < scores.length; row++) {
for (int col = 0; col < scores[row].length; col++) {
// Add the score at current position to total score
totalScore += scores[row][col];
}
}
// Return the total score
return totalScore;
}
// Example usage
public static void main(String[] args) {
// Example 2D array representing player scores
int[][] playerScores = {
{10, 20, 30},
{15, 25, 35},
{5, 10, 15}
};
// Calculate total score
int totalScore = calculateTotalScore(playerScores);
// Print the total score
System.out.println("Total score: " + totalScore);
}
}
This method calculateTotalScore
takes a 2D array scores
of integers representing player scores. It iterates over each element of the array using nested loops, adding each score to a totalScore
variable. Finally, it returns the total score.
In the main
method, an example usage of this method is shown with a sample 2D array playerScores
, and the total score is printed out.