As we have now learnt about variables, operators and expression. Now we can dig into the first control statements for Java. Control Statements defines the control of your program and gives you the ability to change the course of execution statement.
This post will brief you on the first control flow statement that is if-then and if-then-else.
If-then is used to execute a line of code or a code block (group of statements) only when certain condition is true
. For Example let's suppose you are creating program for bank account and you have created a Withdraw method to withdraw money from the account. To execute the Withdraw method you first need to check if the account has balance greater than the amount that needs to be withdrawn. You can do this by
if(accountBalance >= withdrawAmount){ Withdraw(withdrawAmount); }
else
condition is executed when the if condition is not true. If we can modify the previous example to include the else condition as well then
if(accountBalance >= withdrawAmount){ Withdraw(withdrawAmount); }else{ System.out.println("Your account does not have enough balance"); }
You can apply if condition on else statements as well. This can be used when you have to handle multiple scenario's and only one of them will be true. We can modify the about example to accomodate else if
conditions as well.
if(primaryAccountBalance >= withdrawAmount){ Withdraw(withdrawAmount); }else if(secondaryAccountBalance >= withdrawAmount){ Withdraw(withdrawAmount); }else if(emergencyFundBalance >= withdrawAmount){ Withdraw(withdrawAmount); }else{ System.out.println("Any of your account does not have enough balance"); }
Exercise Question
1. Create a class which is used to assign bonus marks to student depending upon their current score. If a student scores between 80 to 100, add 5 bonus points to their score. If the student scores between 60 to 80 add 3 bonus points to their score. If a student scores between 40 to 60 add 1 bonus point to their score. (Make adjustments in your code so that score cannot be greater than 100 after adding bonus points)