Passing parameters BY VALUE

  1. A parameter is passed by value if:

  2. Java ALWAYS passes parameters by value:

    Example:
          public class BankAccount
          {
    	 ...
    	 public void deposit(double amount)
    	 {
    	    ...
    	 }
          }
    
          public class myProgram
          {
    	 public static void main(String argv[])
    	 {
    	    BankAccount harrysChecking = new BankAccount();   
    	    double amount = 200.0;
    
    
    	    harrysChecking.deposit(amount);
    	 }
          }
    
    

    Pictorially:

    A very concrete example:

  3. Now you should completely understand why we wrote:

    
          public void deposit(double amount)
          {
    	 this.balance = this.balance + amount;     
          }
    
    

    (See this lecture from the past: click here)

  4. A common programming error:

    Question: what value of   i is printed ?
          public class myClass
          {
    	 public void trickyMethod(int a)
             {
    	    a = a + 1;   // Programmer thinks
    			 // this can update i
    			 // in main(). WRONG !
    	 }
          }
    
          public class myProgram
          {
    	 public static void main(String argv[])
    	 {
    	    myClass x = new myClass();
    	    int i = 10;
    
    	    x.trickyMethod(i);
    	    System.out.println("Value of i = " + i);    
    	 }
          }