Professional Documents
Culture Documents
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.
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.
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 {
The above is the example with different parameter names. The result is the same. This
depicts the pass by value in Java.
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.