Skip to content
Advertisement

Trouble undestanding this piece of code from codeAcademy Java methods

Can someone please explain to me why in withdraw() it needs to add a return, but in deposit() it doesnt need it?

public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public void checkBalance(){
    System.out.println("Hello!");
    System.out.println("Your balance is " + balance);

  }

  public void deposit(int amountToDeposit){
    balance = balance + amountToDeposit;
    System.out.println("You just deposited " + amountToDeposit); 

  }

  public int withdraw(int amountToWithdraw){
    balance = balance - amountToWithdraw;
    System.out.println("You just withdrew " + amountToWithdraw);
    return amountToWithdraw;

  }

  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    

    //Withdrawing:
    savings.withdraw(150);
    
    //Deposit:
    savings.deposit(25);
    
    //Check balance:
    savings.checkBalance();
    
  }       
}

Advertisement

Answer

The return keyword means “give this value back to the caller”.

withdraw() gives the caller back an int, deposit() gives the caller back nothing. Since deposit() doesn’t give any info back to the caller, it doesn’t return anything. You can see this in the function signaturedeposit() has return type void, while withdraw() has return type int

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement