29 Sep 2014
Pass by reference vs Pass by value in java
Pass by value
Methods become very poewerful by using parameters. In method signature a number of paramters of primitive data type can be defined. When calling a method you must have to provide arguments. For example, the following program print n value and int n is a formal parameter in this method and will accept one argument of type int.
public void printN(int n){ System.out.println(n); }
Note :
- When a method is called with a parameter, the value of argument is passed to parameter is known as pass by value
- if the argument is a variable then value of variable is passed to parameter
- The arguments must match the order of parameter
- The number of arguments must be same as number of parameters
- The type of arguments must be compatible as defined in method signature
Pass by reference
- if we can pass primitive (int and double ) values then we can also pass objects
- Passing an object, actually we are passing the reference of an object
- Java uses only one mode of passing arguments that is passing by value. When an object is passed actually it will send a value representing that object. This value is a reference to that object. We have two type of values here : passing primitve type of value and reference type of value
Example 1:
Example 2:
Memory Allocation Diagram
References
[1] Introduction to Java Programming, Comprehensive Version plus MyProgrammingLab with Pearson eText (9th Edition)
No Responses