If/else Statements
An "if/else and else if" is a simple control flow statement that allows you to execute a particular block of code based on a condition. The condition needs to evaluate to either true or false. Take a look at the example below.- class Program {
- public static void main(String args[]){
- int age = 13;
- if (age > 11){
- System.out.println( "You must be in secondary school");
- }else{
- System.out.println( "You must be in primary school");
- }
- }
- }
The sample code above demonstrates a simple control flow statement. Notice how the statement can execute different blocks of code based upon the value of variable age. This type of statement is useful for "one or the other" type of situations - if the condition evaluates to true then do something, "else" do another thing. However there are situations where you might want to check several conditions. The code sample below shows how to use "else if" to check for several conditions before finally resulting to "else" if none of the conditions evaluated to true.
- class Program {
- public static void main(String args[]){
- String fruit = "Orange";
- if (fruit == "Apple"){
- System.out.println( "So you like apples?");
- } else if (fruit == "Orange"){
- System.out.println( "Oranges are nice");
- } else if (fruit == "Grape"){
- System.out.println( "Not so fond of grapes");
- } else {
- System.out.println( "I like " + fruit);
- }
- }
- }
No comments:
Post a Comment