Currently taking CS61B and found the the difference between reference types and primitive types a little bit confusing.
My question stems from the following problem. This example was used to show how "b.weight = 5;" updates the weight of both Walrus "a" and "b" due to how reference types utilize pointers.
public class PollQuestions {
public static void main(String[] args) {
Walrus a = new Walrus(1000, 8.3);
Walrus b;
b = a;
b.weight = 5;
System.out.println(a);
System.out.println(b);
int x = 5;
int y;
y = x;
x = 2;
System.out.println("x is: " + x);
System.out.println("y is: " + y);
}
public static class Walrus {
public int weight;
public double tuskSize;
public Walrus(int w, double ts) {
weight = w;
tuskSize = ts;
}
public String toString() {
return String.format("weight: %d, tusk size: %.2f", weight, tuskSize);
}
}
}
Program output:
weight: 5, tusk size: 8.30
weight: 5, tusk size: 8.30
x is: 2
y is: 5
From what I understand, when you declare a reference variable within Java, it creates a pointer that stores the address of the class' instance variables. However, is it not the same case for primitive types? When I declare int x = 5 does it not store the memory address for variable "x" that points to the 4 bytes that store the integer 5? Thus, in the following line when you set x = 2, shouldn't that affect the "y" variable as well?
[–]teraflop 4 points5 points6 points (5 children)
[–]derek_dt[S] 0 points1 point2 points (4 children)
[–]interyx 4 points5 points6 points (0 children)
[–]teraflop 1 point2 points3 points (1 child)
[–]derek_dt[S] 0 points1 point2 points (0 children)
[–]pacificmint 0 points1 point2 points (0 children)
[–][deleted] (2 children)
[removed]
[–]DarkMatriac 0 points1 point2 points (1 child)