I am learning about References and Datatypes in Java and this particular code is still confusing me. I understand that all of the primitive types in Java are value types (byte, short, int, long, float, double, boolean, char), and when you're using a string or an object it's a reference type. When I was taught to declare and initialize a variable, I was told to think of it like creating a box. So if I create a variable "y" and give it a value of "5" it's like I've created a box called "y" that contained the value of 5. My teacher said that if I then try to call y in a method (check out the code below for more detail) the value will remain untouched because it's a primitive datatype so I'm only passing in 5, not the variable that CONTAINS 5. Well I'm confused because if I'm passing in the value of 5, why wouldn't the following method add one onto it.
public class ReferenceAndValueTypes {
public static void main(String[] args) {
int y = 5;
addOneTo(y);
System.out.println(y);
}
static void addOneTo(int number){
number = number + 1;
}
}
The output is 5 and that confuses me greatly. The teacher says it's because int is a value type so we're not passing the y variable in, and we're not operating on that variable but rather the value of that variable. However, the value of that variable is 5 and since the method adds one, shouldn't it be 6? Or, is it because y is a value type, the method cannot work with it so it just has to print out the initial value of y which was 5?