Tuesday, June 1, 2021

Java Tutorial: if-then, if-then-else and switch statements

Chapters

if-then Statement

Hello Everybody! This is brainy ghosts and today we're gonna discuss the if-then, if-then-else and switch statement which are parts of the java control flow statement. If-then statement is the most basic component of the control flow statement.
General Form: if(cond){//code to execute}

Example:
public static void main(String[]args){
  boolean condition = true;
      
  if(condition == true){
     System.out.println("condition is true");
  }
}

Try changing the value of condition variable to false and the program won't execute the println() in the if-then(or just if) statement.

we can put initializing expression in the if parentheses while formulating a condition. This will also work in switch and else-if parentheses.
public static void main(String[]args){

  int num = 3;
  
  //(num = ++num) is the initializing
  //expression
  if((num = ++num) > 3)
    System.out.println("num("+num+") is greater than 3!");
  else
    System.out.println("num("+num+") is less than 3!");
}

if-then-else Statement

This statement is very similar to if-then but with additional else block. This block will execute if the condition in if block is not true.
General Form:
if(cond){
  //code to execute
}
else{
  //code to execute
}
Example:
public static void main(String[]args){
  boolean condition = false;
      
  if(condition == true){
     System.out.println("condition is true");
  }
  else{
    System.out.println("condition is false");
  }
}
if-else-if Statement

Use this statement if you need to test multiple conditions. We have additional block here which is the else if() block.
General Form:
if(cond){
  //code to execute
}
else if(cond){
  //code to execute
}
else{
  //code to execute
}
The else block is optional. You can omit that block. If all conditions are false then code in else block will be executed, if there's one.
Example:
public static void main(String[]args){
  String foo = "small";
  String bar = "large";
  
  if(foo.equals("large") == true && 
     bar.equals("small") == true){
     System.out.println("foo is large and bar is small");
  }
  else if(foo.equals("small") == true &&
          bar.equals("large") == true){
  	 System.out.println("foo is small and bar is large");
  }
  else if(foo.equals("small") == true &&
          bar.equals("small") == false){
  	 System.out.println("foo is small but bar is not small");
  }
  else{
    System.out.println("All conditions are false.");
  }
}
This statement is evaluated from top to bottom, starting at if() block. if one of the conditions is true then other conditions below it won't be evaluated.

The equals() method is a pre-defined method in String class that compares the values of two strings. It returns true if two strings are equal, false otherwise. We will learn about methods in future tutorial.

Switch Statement

This statement is very similar to if statement with new syntax. Use this statement if you want to evaluate multiple possible values of a variable.
General Form:
switch(value){

    case value1:
    //code to execute
    break;
    ...
    
    default:
    //code to execute
    break;

}
"..." means you can put any number of possible values in the statement. default is optional and has the same purpose as the else statement in if-else-if: it will be executed if the value of the "value" variable doesn't match any possible values that we put in the switch statement. default will be also executed if a break before it is omitted. We will learn about omitting the break keyword in the switch statement later.
Example:
public static void main(String[]args){
 String bar = "large";
 
switch(bar){
   case "small":
   System.out.println("bar is small");
   break;
   
   case "medium":
   System.out.println("bar is medium");
   break;
   
   case "large":
   System.out.println("bar is large");
   break;
   
   default:
   System.out.println("No Possible Match!");
   break;
 }
}
break can be omitted if we want to. The purpose of break is to stop the execution in the switch block once a match is found. Omitting break makes the execution in the switch statement continue even a match is found.
Example:
public static void main(String[]args){
 String cat = "large";
 
   switch(cat){
     case "small":
     System.out.println("cat is small");
     cat = "cute";
			
     case "cute":
     System.out.println("cat is cute");
     break;
   
     case "large":
     System.out.println("cat is large");
     cat = "fluffy";
			
     case "fluffy":
     System.out.println("cat is fluffy");
     break;
			
     default:
     System.out.println("No Possible Match!");
     break;
   }
}
Result
cat is large
cat is fluffy

Differences between if and switch statement

We already know that if statement is preferrable when dealing with conditions whereas switch statement is preferrable when dealing with matching criteria. Other differences are:

1.) switch doesn't accept boolean values whereas if statement does.
Example:
public static void main(String[]args){
  boolean condition = true;
 
   switch(condition){
     case true:
     System.out.println("condition is true");
     break;
     
     case false:
     System.out.println("condition is true");
     break;
   }
}
You will encounter an error if you compile this code above. We already know if statement accepts boolean values.

2.) switch doesn't accept null value whereas if statement does.
Example:
public static void main(String[]args){
  String cat = null;
 
   switch(cat){
     case "small":
     System.out.println("cat is small");
     break;
     
     case "big":
     System.out.println("cat is big");
     break;
   }
}
You will encounter an error if you compile this code above. Let's try null value in the if statement.
Example:
public static void main(String[]args){
  String cat = null;
 
   if(cat == null){
     System.out.println("Oh! Ow! cat doesn't exist!");
   }
}
This code above will be compiled without errors.

Omitting some keywords and tokens in if statement

We can remove some tokens like braces in if statement if we meet these conditions:
1.) Braces can be removed if there's only one statement in the body of if,else if and else block
Example:
public static void main(String[]args){
  String cat = "small";
 
   if(cat.equals("small") == true)
     System.out.println("cat is small");
   else if(cat.equals("large") == true)
     System.out.println("cat is large");
   else
     System.out.println("No Match");
     
}
Note: if-else and if-else-if statements behave like a single statement. So this syntax is legal.
if(true)
  if(true)
  else
However, I don't recommend the syntax above to be used 'cause it can make your code messy and confusing that may cause unexpected results. When creating a complex branching statement please add braces.

Tip: if you use if-else or if-else-if statement and, for example, else or else if statement is a block, then the statement above should be a block too.
Example:
public static void main(String[]args){
  String cat = "small";
 
   if(cat.equals("small") == true){
     System.out.println("cat is small");
   }
   else{
     System.out.println("Cat is not small");
     System.out.println("But I still love my cat");
   }
}
This code above is alright and more readable.

2.) We are not required to compare a boolean variable or a method that returns boolean value to the "true" and "false" keywords.
Example:
public static void main(String[]args){
  String cat = "small";
  boolean condition = true;
 
   if(cat.equals("small"))
     System.out.println("cat is small");
   else if(!cat.equals("small"))
     System.out.println("cat is not small");
     
   if(condition)
     System.out.println("condition is true");
   else if(!condition)
     System.out.println("condition is false");
}
This syntax might be confusing for beginners but this will make your code more tidy.

Nested if and switch statement

if and switch statement, like other statements, can be nested. Here's an example.
Example:
public static void main(String[]args){
  String catSize = "small";
  int catAge = 4;
 
   switch(catSize){
   
     case "small":
     System.out.println("cat is small");
     
     if(catAge >= 1 && catAge <= 3)
       System.out.println("cat is young.");
     else if(catAge >= 4 && catAge <= 5)
       System.out.println("cat is growing up.");
     else 
       System.out.println("cat is small and more than 5 yrs old.");
     break;
     
     case "large":
     System.out.println("cat is large");
     
     if(catAge >= 5 && catAge <= 10)
       System.out.println("cat is getting old.");
     else if(catAge >= 11)
       System.out.println("cat is immortal.");
     else 
       System.out.println("cat is large and less than 5 yrs old.");
     break;
   
   }
     
}

No comments:

Post a Comment