public class Cat {
String name;
int age;
String color;
String occupation;
public Cat(String name, int age, String color, String occupation) {
this.name = name;
this.age = age;
this.color = color;
this.occupation = occupation;
}
}
public static void main(String[] args) {
Cat MrTibbens = new Cat("Mr.Tibbens", 3, "Black", new Occupation("World Domination"));
Cat Khajiit = new Cat("Khajiit", 5, "White", new Occupation("Thief"));
}
MrTibbens
and Khajiit
of the Cat class they are stored on the stack and the values that they represent however are stored in the heap which the reference is pointing to. So this would be their respective names, age, color, occupation, etc. The object in the stack is “referring” to the value stored in the stack.Reference Type | Description |
---|---|
Annotation | Provides a way to associate metadata (data about data) with program elements. |
Array | Provides a fixed-size data structure that stores data elements of the same type. |
Class | Designed to provide inheritance, polymorphism, and encapsulation. Usually models something in the real world and consists of a set of values that holds data and a set of methods that operates on the data. |
Enumeration | A reference for a set of objects that represents a related set of choices. |
Interface | Provides a public API and is “implemented” by Java classes. |
*Source OREILLY
public class refTest{
public static class House{
private int price;
public House(int price){
this.price = price;
}
public void setPrice(int newPrice){
this.price = newPrice;
}
public int getPrice(){
return this.price;
}
}
public static void main(String[] args){
House house1 = new House(0);
house1.setPrice(500000); // setting house price to $500,000, accessing same spot in memory to change
System.out.println("House Price: " + "$" + house1.getPrice()); // printing the house price that was set
House house2 = new House(0);
house2 = house1; // telling house 2 to reference the same spot in memory as house 1. price should be the same :)
System.out.println("House Price of House 2: " + "$" + house1.getPrice()); // printing the house price that was set
}
}
refTest.main(null);
House Price: $500000
House Price of House 2: $500000
Reference Types | Primitive Types |
---|---|
Unlimited number of reference types, as they are defined by the user. | Consists of boolean and numeric types: char, byte, short, int, long, float, and double. |
Memory location stores a reference to the data. | Memory location stores actual data held by the primitive type. |
When a reference type is assigned to another reference type, both will point to the same object. | When a value of a primitive is assigned to another variable of the same type, a copy is made. |
When an object is passed into a method, the called method can change the contents of the object passed to it but not the address of the object. | When a primitive is passed into a method, only a copy of the primitive is passed. The called method does not have access to the original primitive value and therefore cannot change it. The called method can change the copied value. |
*Source OREILLY
public class PrimitiveTypesExample {
public static void main(String[] args) {
// Declaration and initialization of primitive variables
boolean isJavaFun = true;
char grade = 'A';
byte byteValue = 127; // byte range: -128 to 127
short shortValue = 32000; // short range: -32,768 to 32,767
int intValue = 42;
long longValue = 123456789L; // The 'L' indicates a long literal
float floatValue = 3.14f; // The 'f' indicates a float literal
double doubleValue = 2.71828;
// Displaying values
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Grade: " + grade);
System.out.println("Byte Value: " + byteValue);
System.out.println("Short Value: " + shortValue);
System.out.println("Int Value: " + intValue);
System.out.println("Long Value: " + longValue);
System.out.println("Float Value: " + floatValue);
System.out.println("Double Value: " + doubleValue);
}
}
PrimitiveIterator.main(null);
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);
16
Answer the following questions based on the code above:
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.
(b) Explain the differences between primitive types and reference types in terms of memory allocation and usage in Java programs.
(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.
In Java, there are two major categories of data types: primitive types and reference types.
Primitive Types: These are the most basic kinds of data types and directly contain values. Java provides 8 primitive types which include byte
, short
, int
, long
, float
, double
, char
, and boolean
. They are stored in the call stack, which allows for fast access but has a limited size.
int age = 30;
(An integer value)double salary = 5000.00;
(A double precision floating-point number)boolean isEmployed = true;
(A boolean value true or false)Reference Types: These include any data type that derives from a class or an interface, including arrays. Reference types do not store the actual value, but a reference (or address) to the memory where the value is stored. This memory location is in the heap, which is a larger, but slower-to-access memory area.
String name = "John Doe";
(A String object)Integer ageObject = new Integer(30);
(An Integer object)Customer customer = new Customer();
(A Customer object, assuming a Customer class exists)Memory Allocation:
int
is always 4 bytes.Usage:
calculateInterest
MethodAssuming a Customer
class exists, here is how the calculateInterest
method could be implemented.
public class BankApplication {
/**
* Represents customer information.
*/
static class Customer {
// Assuming there are attributes and methods relevant to a Customer
String name;
// Constructor, getters, setters, etc., are assumed to be defined here.
}
/**
* Calculates the interest based on the principal amount for a given customer.
*
* @param principal The principal amount as a primitive double.
* @param customer The customer for whom the interest is being calculated.
* @return The calculated interest amount as a double.
*/
public static double calculateInterest(double principal, Customer customer) {
final double interestRate = 0.05; // Example interest rate of 5%
// Calculate interest
double interest = principal * interestRate;
// This could include more complex logic based on customer attributes if needed.
return interest;
}
// Example usage
public static void main(String[] args) {
Customer customer = new Customer();
customer.name = "John Doe";
double principal = 10000.00; // Principal amount
double interest = calculateInterest(principal, customer);
System.out.println("Interest for " + customer.name + ": $" + interest);
}
}
Explanation:
calculateInterest
method takes two parameters: a primitive double
type principal
, which represents the principal amount of money, and a reference type Customer
, representing the customer’s information.interestRate
is defined within the method to calculate the interest. This is a simplified example; in a real application, the interest rate might vary based on different factors, possibly including attributes of the Customer
object.main
method, an instance of Customer
is created, and its name
attribute is set. The calculateInterest
method is then called with a sample principal amount and the Customer
object, and the calculated interest is printed to the console.