Java passes arguments by value. Which of the following correctly describes how variables are passed to a method?
Select one:
Both primitive and object types are passed by the value that they refer to in memory.
Primitive types are passed by reference while object types are passed by values stored at the object location in the memory.
A variable is passed to a method and its value will no longer exist within the scope of where the method was originally called.
A variable is passed to a method and the method uses the variable name to access and modify the variable.
Primitive values are passed by value while object types are passed by reference.
Both primitive and object types are passed by the value that they refer to in memory.
EXPLAINATION
Object references are passed by value
All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of the value also changes the real value of the object. To understand why, start with this example:
public class ObjectReferenceExample {
public static void main(String... doYourBest) {
Simpson simpson = new Simpson();
transformIntoHomer(simpson);
System.out.println(simpson.name);
}
static void transformIntoHomer(Simpson simpson) {
simpson.name = "Homer";
}
}
class Simpson {
String name;
}
What do you think the simpson.name
will be after
the transformIntoHomer
method is executed?
In this case, it will be Homer! The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.
Primitive types are passed by value
Like object types, primitive types are also passed by value. Can you deduce what will happen to the primitive types in the following code example?
class Simpson {
String name;
}
public class PrimitiveByValueExample {
public static void main(String... primitiveByValue) {
int homerAge = 30;
changeHomerAge(homerAge);
System.out.println(homerAge);
}
static void changeHomerAge(int homerAge) {
homerAge = 35;
}
}
If you determined that the value would change to 30, you are correct. It’s 30 because (again) Java passes object parameters by value. The number 30 is just a copy of the value, not the real value. Primitive types are allocated in the stack memory, so only the local value will be changed. In this case, there is no object reference.
Get Answers For Free
Most questions answered within 1 hours.