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){

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:
Pass by reference example

Pass by reference

Example 2:

Student Class [1]

Pass by reference Example 2

Pass by reference Example 2[1]

Memory Allocation Diagram

Passing a student object

Passing a student object[1]

Passing a student Object

Passing a student Object[1]


[1] Introduction to Java Programming, Comprehensive Version plus MyProgrammingLab with Pearson eText (9th Edition)

No Responses

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.