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)
public class Swap1 {
  public static void main( String[ ] args ) {
    int a = Integer.parseInt( args[0] );
    int b = Integer.parseInt( args[1] );
    // Invoke the swap method.
    swap( a, b );
    System.out.print( a + " " + b );
  }

  public static void swap( int a, int b ) {
    // Swap a with b.
    int c = a;
        a = b;
        b = c;
  }
}
shell> java Swap1    

Output:           Result:

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)
public class Swap2 {
  public static void main( String[ ] args ) {
    Obj a = new Obj( Integer.parseInt( args[0] ) );
    Obj b = new Obj( Integer.parseInt( args[1] ) );
    // Invoke the swap method.
    swap( a, b );
    System.out.println( a.getVal( ) + " " + b.getVal( ) );
  }

  public static void swap( Obj a, Obj b ) {
    // Swap a with b.
    int c = a.getVal( );
    a.setVal( b.getVal( ) );
    b.setVal( c );
  }
}

class Obj {
  private int val;
  public Obj( int number )         { val = number; }    // a constructor
  public void setVal( int number ) { val = number; }
  public int  getVal( )            { return val; }
}
shell> java Swap2    

Output:           Result:




      Go beyond the show by going behind the scenes.