Tuesday, 1 February 2011

Method arguments are always passed by value

This includes object references which also passed by value and copied. However in this case the object itself is not copied and you end up with two references to the same object.

Consider the output from the code below:

public class Test {
 
        public static void main(String[] args){ 
        int x=5, y=7; 
        swap(x,y); 
        System.out.println("x = " + x + ", y = " + y ); 
    } 

    /*
     * Swap our two variables around
     */
    static void swap(int a, int b) {  
         
         int c = a;                  
         a = b; 
         z = c; 
    } 
}

Using the above idea the output will be: x = 5, y = 7

No comments: