Revisit pass by value

To be succinct, both Java and C are always pass-by-value.
Admittedly, if a java method has an object argument, when it's called, it would receive a reference, however, this is not pass-by-reference.
pass-by-value means there is a copy passed, rather than the original value/reference, for java, a callee with object argument actually receives a copy reference, rather than the original reference, this copy reference has same value of the original reference. Therefore, if give the copy reference a new reference, the original reference would not be affected.

Here's an example:

public void switchAccount(Account account){
    account.setCurrency("GBP");  
    account = new Account();
    account.setAccountName("magnate");
}

public static void main(String[] args){
    Account account1 = new Account();   
    account1.setAccountName("indictment");
    switchAccount(account1);
    System.out.println(account1.getAccountName());
    System.out.println(account1.getCurrency());
}
Since both copy refernce and original reference refer to account1, thereby the following line would take effect:

account.setCurrency("GBP"); 
Although

account = new Account();
gives the copy reference a new value(object address), the original reference remains intact, hence, account1's name would not change.


Reference
1. The C Progmming Language. K&R
2. http://stackoverflow.com/questions/40480/is-java-pass-by-reference


你可能感兴趣的:(Revisit pass by value)