Passing Parameters
Passing Parameters by Value
Parameters are passed by value (not by reference) to methods.
Through this, the argument value is passed to the parameter.
The following program shows an example of passing parameter by value.
The values of the arguments remain the same even after the method invocation:
Swap1.java (call by value)
|
|
02 | public static void main( String[ ] args ) { |
03 | int a = Integer.parseInt( args[ 0 ] ); |
04 | int b = Integer.parseInt( args[ 1 ] ); |
07 | System.out.print( a + " " + b ); |
10 | public static void swap( int a, int b ) { |
|
|
Swapping by Using Objects
Java does not support the method of calling by reference.
The following script tries to bypass the limit by using objects to swap two values:
Swap2.java (swapping by using objects)
|
|
02 | public static void main( String[ ] args ) { |
03 | Obj a = new Obj( Integer.parseInt( args[ 0 ] ) ); |
04 | Obj b = new Obj( Integer.parseInt( args[ 1 ] ) ); |
07 | System.out.println( a.getVal( ) + " " + b.getVal( ) ); |
10 | public static void swap( Obj a, Obj b ) { |
13 | a.setVal( b.getVal( ) ); |
20 | public Obj( int number ) { val = number; } |
21 | public void setVal( int number ) { val = number; } |
22 | public int getVal( ) { return val; } |
|
|