What is Pass by value?
Pass by value means passing a value as an argument to a method.
What is Pass by reference?
In Pass by reference, passing the address itself to a method.
Java always support pass by value. It means we pass copy of variable value to a method, it’s may be either primitive variable or object reference variable, java will always pass copy of bits representing the value of a variable.
Passing primitive variables
When you are passing the primitive variables, you actually pass copy of variable value to a method. For ex. If you are passing int value 5 to a method, you are passing copy of bits representing value 5 to a method. The called method receives the copy of value and does whatever it likes. The value of the original variable cannot be changed within the called method. Let see example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<strong> public</strong> <strong>class</strong> Test { <strong> public</strong> <strong>static</strong> <strong>void</strong> main (String [] args) { int a = 6; Test t = <strong>new</strong> Test(); System.<em>out</em>.println("Before passing value of a = " + a); t.modify(a); System.<em>out</em>.println("After passing value a = " + a); } <strong> void</strong> modify(<strong>int</strong> b) { b=7; System.<em>out</em>.println("Value of b = " +b); } } |
Output :
Before passing value of a = 6
Value of b = 7
After passing value a = 6
Passing Object Reference Variable
The reference variable points to the object which is on the heap. The reference variable actually holds the bits representing the particular object on the heap. In pass by object reference variable you pass copy of reference variable to a called method.
For Ex:
Dog d1 = new Dog();
Dog d2 = d1;
In the above example, you can see both reference variables are pointing to same object on the heap. Let see an example where we are modifying same object.
1 |
<strong></strong> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<strong>public</strong> <strong>class</strong> ObjectTest { <strong> public</strong> <strong>static</strong> <strong>void</strong> main (String [] args) { ObjectTest t = <strong>new</strong> ObjectTest(); StringBuffer sb = <strong>new</strong> StringBuffer("Hello World"); System.out.println(sb); t.display(sb); System.out.println(sb); } <strong> public</strong> <strong>void</strong> display(StringBuffer str) { str = str.insert(6, "Java "); } } |
Output:
Hello World
Hello Java World
Leave a Reply