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();
}
}
CodePudding user response:
That is because in the definition of your withdraw()
method, it is stated that it should return an int.
In the deposit()
method you use void as a return type. When using void, no return
is needed. (But you could still also just use an empty return;
at the end of the method if you want to)
CodePudding user response:
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 signature - deposit()
has return type void
, while withdraw()
has return type int