Scanner class Methods in Java

Passing Arguments : Pass by Value

  Passing Arguments to Methods

While using methods we require to pass arguments or parameters to the method. If you remember using methods in previous post. Then you might have noticed that we pass some values in methods even in constructors. We use arguments like, 1,"Hi",4.5,'a' ,num1,num2 etc or we may require to pass objects as arguments.

There are two ways of passing arguments to methods or constructor in java:-

  1. Pass by Value
  2. Pass by Reference

Pass By Value


When we pass a variable of primitive type to method as a parameter then the copy of the variable is created and used for modifications. It does not modify the actual arguments.This is best approach when we do not want to change the original value of the argument stored in memory.In this way, we can retrieve  original value whenever we want and can check that the changes we have made are not reflected in the original value of variable.

Example: This example will illustrate the use of pass by value method to pass arguments to a method in java.

Write a program to show the use of pass by value while passing arguments or parameters.


Example of Pass by Value 

In the above program,

  1. After main method, we have declared a method "increment()" which contains the code to increase the value of parameter by 1000. This method takes an argument of integer type "num". In the method body ,we are increasing the number by 1000.And print statements is used to print the increased number.
  2. In the body of main method, we declared "number" and assigned it value of 5.This is original value of number variable.It originally holds the value of 5.
  3. The first print statement is printing the actual value of "number" on screen.
  4. The "increment(number)" is a method call.It invokes the static method that we previously created to increment the number.Here, we are passing the "number" as an argument.And this number holds an actual value of primitive type. Hence, this is the process of  Pass by Value.
  5. When this method is invoked, it will increase the number 5 by 1000 and prints 1005 on screen using method's print statement.
  6. At the end, we wrote a print statement to print the value of "number" variable.It will print the value of variable after all calculations.
Output:

pass by value method to pass arguments to a method in java.

Here, you can see the last statement prints the original value of variable that we assigned to it.So, 5 is the actual value that variable holds.In pass by value method, the original value of variable remains same as it creates the copy of variable and does not modify the original variable.

In the later post, we will discuss Pass by Reference. Happy Coding!

Comments