Complete the Primitive types vs references exercises with calls before reviewing the solutions.
Review the primitive exercise solution with AP CS Tutor Brandon Horn.
Original code
public static void main(String[] args)
{
int a = 10;
primitive(a);
System.out.println(a);
}
private static void primitive(int b)
{
b = 15;
}
Output
10
Explanation
All arguments in Java are passed by value. The call primitive(a);
passes a copy of the value of a
, which is 10, to the primitive
method. Changes to the value of the parameter b
have no effect on the value of a
.
Step by step memory diagram
Step 1
public static void main(String[] args)
{
int a = 10;
// more code not yet run
}
Memory diagram after Step 1
a: 10
Primitive type variables store their values directly. The value of a
is 10
. There is no object and no reference.
Step 2
public static void main(String[] args)
{
int a = 10;
primitive(a);
// more code not yet run
}
private static void primitive(int b)
{
// more code not yet run
}
Step 2 is immediately after the call to the primitive
method, but before any code inside the primitive
method has been run.
Memory diagram after Step 2
a: 10
b: 10
All arguments in Java are passed by value. The call primitive(a);
passes a copy of the value of a
, which is 10
, as the initial value of the parameter b
. a
and b
are not linked together.
A parameter listed in a method header, such as int b
, is sometimes called a formal parameter. A value passed to a method during a call, such as 10
, is sometimes call an actual parameter or argument.
Step 3
public static void main(String[] args)
{
int a = 10;
primitive(a);
// more code not yet run
}
private static void primitive(int b)
{
b = 15;
}
Step 3 is immediately after execution of the statement b = 15;
, but before the primitive
method returns.
Memory diagram after Step 3
a: 10
b: 15
The statement b = 15;
sets the value of b
to 15
. The value of a
remains unchanged. a
and b
are not linked together.
Step 4
public static void main(String[] args)
{
int a = 10;
primitive(a);
System.out.println(a);
}
private static void primitive(int b)
{
b = 15;
}
Step 4 is after the primitive
method returns and after the print
statement executes.
Memory diagram after Step 4
a: 10
The scope of parameters is the method in which they are defined. When the primitive
method returns (ends), the variable b
no longer exists.
Output after Step 4
10
The main
method prints the value of a
, which is 10
.