Side Effects

public void transfer(double amount, BankAccount other)
{
   balance = balance - amount;
   other.balance = other.balance + amount; //
Modifies explicit parameter
}

public void printBalance() // Not recommended
{
   System.out.println("The balance is now $" + balance);
}


If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect?

   Answer: No – a side effect of a method is any change outside the implicit parameter.

 


Consider the DataSet class of Chapter 6. Suppose we add a method
void read(Scanner in)
{
   while (in.hasNextDouble())
      add(in.nextDouble());
}

 

Does this method have a side effect?

   Answer: Yes – the method affects the state of the Scanner
   parameter.


In Java, a method can never change parameters of primitive type

for example,

double savingsBalance = 1000;
harrysChecking.transfer(500, savingsBalance);      
System.out.println(savingsBalance);      
...
void transfer(double amount, double otherBalance)      
{
   balance = balance - amount;
   otherBalance = otherBalance + amount;
}

savingBalance to otherBalance - ONLY pass by value, no pass by reference in JAVA.

Call by Value and Call by Reference