You are on page 1of 3

Is it a Pass By Value or a Pass By Reference in Java?

First of all what are these 2 terms?

I cover just pass by value here.

In Java, we have methods. Let us take a simple method Math.abs(). If you say Math.abs(-
4) it means you are passing argument ‘-4’ which is a constant, to your method ‘abs’ of
Math class.
If we say Math.abs(num), we are passing an argument which is a variable to your method
‘abs’ of Math class.

There is an important principle involved here.

If a variable is passed to a method in our case ‘num’, the method myabsvalue receives a
copy of the variable’s value. The value of the original variable cannot be changed within
the method. So, a method will have access only to the copy of the variable but not to the
original variable. This process is called pass by value.

public class Main {

public static void myabsvalue(int num)


{
System.out.println("I am in method myabsvalue");
num = Math.abs(num);
System.out.println(num);
}

public static void main(String[] args) {


// TODO code application logic here
int num = -4;
System.out.println("Number is:"+num);
myabsvalue(num);
System.out.println("I am in main method");
System.out.println("Value of num is:"+num);

In the method myabsvalue, I am defining num again, I say ‘int num’ in my parameter list.
So, the scope of num is only in the method myabsvalue. So, that is basically equivalent to
defining a new variable. It is different from the ‘num’ I defined in the main method.
public class Main {

public static void myabsvalue(int mynumber)


{
System.out.println("I am in method myabsvalue");
mynumber = Math.abs(mynumber);
System.out.println(mynumber);
}

public static void main(String[] args) {


// TODO code application logic here
int num = -4;
System.out.println("Number is:"+num);
myabsvalue(num);
System.out.println("I am in main method");
System.out.println("Value of num is:"+num);

The above is the example with different parameter names. The result is the same. This
depicts the pass by value in Java.

Talking of scope, it is described below:

In your main method define the below

for(int i=0; i<3;i++)


System.out.println(i);
i = 5; // we see an error saying i is undefined.

This is because variables can’t be used before they are declared, or after the end of their
scope. What are the Java rules for scope in case of local variables?
1) A variable’s scope extends from the line it is declared until the end of the block it
is contained in
2) A formal parameter’s scope is the entire method. What is a formal parameter?
They are the variables declared in the parameter list of a method. In our case ‘int
num’ in the method myabsvalue.
3) A variable declared in the ‘for’ loop control has a scope that extends to the end of
‘for’ loop.
P.S : A local variable is the one which is accessible only within the function or block
where it is declared.

Pass By Reference: Later.

You might also like