OCA Java SE 8 Method - Java Parameter Passing








Java is a "pass-by-value" language.

A copy of the variable is made and the method receives that copy.

Assignments made in the method do not affect the caller.

Let's look at an example:

2: public static void main(String[] args) { 
3:   int num = 4; 
4:   newNumber(5); 
5:   System.out.println(num);     // 4 
6: } 
7: public static void newNumber(int num) { 
8:   num = 8; 
9: } 

On line 3, num is assigned the value of 4.

On line 4, we call a method. On line 8, the num parameter in the method gets set to 8.

The variable on line 3 never changes because no assignments are made to it.

What is the output of the following code.

public static void main(String[] args) { 
  String name = "AAA"; 
  speak(name); 
  System.out.println(name);  
} 
public static void speak(String name) { 
  name = "BBB"; 
} 

The correct answer is AAA. The variable assignment is only to the method parameter and doesn't affect the caller.

We can call methods on the parameters.

In the following code, we have code that calls a method on the StringBuilder passed into the method:

public static void main(String[] args) { 
  StringBuilder name = new StringBuilder(); 
  speak(name); 
  System.out.println(name); // AAA 
} 
public static void speak(StringBuilder s) { 
  s.append("AAA"); 
} 

In this case, the output is AAA because the method calls a method on the parameter.





Pass-by-Value vs. Pass-by-Reference

Java uses pass-by-value to get data into a method. Assigning a new primitive or reference to a parameter doesn't change the caller.

Calling methods on a reference to an object does affect the caller.

For getting data back from a method, a copy is made of the primitive or reference and returned from the method.