Pass by value

Java is always pass by value. Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Java uses JVM Stack memory to create the new objects that are formal parameters. This newly created objects scope is within the boundary of the method execution. Once the method execution is complete, this memory can be reclaimed. So, when calling a method

  • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive.
  • For objects, the pass by value is the value of the reference to the object.

 

Variable Number of Arguments

A method can receive a variable number of arguments with the use of ellipsis (three consecutive dots: …). In order to do so, the data type of the variable number of arguments which can be even a reference type is stated followed by the ellipsis and an identifier. This type can be used not more than once in a method header and should be the last of all parameters.

public void meth (double a, int... b) // valid
public void meth( int[]... a) // valid - reference types are also allowed

 

The arguments received are stored in an array of the same data type as specified in the method header having a length equal to the number of arguments passed. Therefore, those elements can be accessed as we access an array passed to an array type parameter.

 

Passing array to function

public static void passArray(String[] name)

// You'd call it with
String [] arr = new String[3];
passArray(arr);

 

Parameter Vs. Argument

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.