Topics Covered

On this section of my java tutorial series we will be covering topics regarding the different conditional statements available according to java specification. The following topics will be covered:

  • if then
  • if then else
  • switch statements

Overview

For every programming language that i have handled, there will always be a conditional statements. Java is no different, it uses the condition statements to control the flow of the program. This is very important, since at some point we have to satisfy conditions in order to proceed further on our code. Like for instance an input of yes or no from the console will decide if the program will continue or would it be terminated. This is handled by using conditional statements.

Let’s tackle this topic thoroughly.

If then statement

The if-then condition is the most basic of  the conditional statements in java. This tells the program to execute a code block if the condition has been satisfied or it returns true.

Let’s take an example

package com.javatutorial.example;

/*
 * This is demo program 
 * in using if-then conditional statement
 */

public class IfConditionDemo {

	public static void main(String[] args) {
		
		int x = 6;		
		if(x>5){
			System.out.println("Threshold breach");
		}	

	}

}

Initially we have declared x = 6. So the condition x > 5 will evaluate to true thus the code block  System.out.println(“Threshold breach”); will get executed. This code block basically just prints to the console “Threshold breached”. What if we have declared x to have a value of 4, will the “Threshold breached” be printed out on the console. The answer would be no, because the condition x>5 will return false.

Let’s take a more complicated example for you to better understand it.

package com.javatutorial.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

/*
 * This is demo program 
 * in using if-then conditional statement
 */

public class IfConditionDemo {

	public static void main(String[] args) throws IOException {
		
		// generate random number 1-100
		int min = 1;
		int max = 100;
		Random random = new Random();
		boolean repeat = true;
		while(repeat){
			int randInt = random.nextInt((max - min) + 1) + min;
			//print a random number generated
			System.out.println("Random Number:"+randInt);
			// ask the user if s/he wants to generate another random number
			System.out.print("Do you want to generate another (y/n)?");
			// read the user input using bufferedReader
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String strVal = br.readLine();
			System.out.println(strVal);
			
			// check the user input
			if(strVal.equals("n")||strVal.equals("N")){
				repeat=false;
			}		
		}	
	}
}

 

Basically the above example is just to generate a random random number and depending on the user input, it keeps generating if the user input is “Y” or “y”. Initially we have set the boolean variable repeat to true and we used that variable in our for loop. Since the we have set the repeat variable to true, the loop will get executed. The code block in generating a random number will get in first and then after we print out the random number, we asked the user if s/she wants to get random number. This is accomplished by calling the BufferedReader class from the java API. Maybe it’s not yet very clear to you the different packages available in java, however as we go along I will introduce it one by one. So chill out. Moving on, we use the if-then condition to evaluate the user input. If the user input is “n” or “N” as we have declared inside our if condition, the variable repeat is assigned a false value. This will invalidate the while loop condition while(repeat).

if-then else

The if-else just purely evaluate a certain condition and execute a code block, the if-then else provides another path of execution.

Let’s tackle first a simple if-else condition. Basically if the if condition returns true then the else code block will get executed

		if(x>=5){
			System.out.println("Threshold Breached");
		}
		else{
			System.out.println("Still in range");
		}

The above example just demonstrated on how if-else condition works. Any numbers that satisfy the condition x>=5 will print on the console that “Threshold Breached” else a message “Still in range” will get printed. A little exercise, if x is 10, what message will get printed? It will print “Threshold breached”. But what if x is 1? The console will print “Still in range”. It’s very easy, isn’t it?

Most of the time the if-else condition is all just you need, however what if from our example above we need to add another condition that if x is < 3 , message is “Less than the threshold”. How could we accomplished that? We can use if, else if, and then else. Let’s take a look on the implementation of our example.

		if(x>=5){
			System.out.println("Threshold Breached");
		}
		else if(x<3){
			System.out.println("Less than the threshold");
		}
		else{
			System.out.println("Still in range");
		}

Technically, all numbers greater than 4 will print “Threshold breached”, moreover all numbers less than 3 will print “Less than the threshold”. So on what condition will the code prints “Still in range”? The values 3 and 4 will satisfy the else condition.

switch

Using the if-then else condition statements is very effective to be used if the condition statements are small. But if the required else if already reached to a point wherein the code becomes messy, the use of switch statements become practical.

The switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). Below is a simple example on the use of switch statement

 

package com.javatutorial.example;


/*
 * This is demo program 
 * for case statement
 */

public class CaseDayOfWeekDemo {

	public static void main(String[] args) {
		
		
		int dayOfWeek = 3;
		switch(dayOfWeek){
		case 1: 
			System.out.println("Monday");
			break;
		case 2: 
			System.out.println("Tuesday");
			break;
		case 3: 
			System.out.println("Wednesday");
			break;
		case 4: 
			System.out.println("Thurday");
			break;
		case 5: 
			System.out.println("Friday");
			break;
		case 6: 
			System.out.println("Saturday");
			break;
		case 7: 
			System.out.println("Sunday");
			break;
		}	

	}

}

The dayOfWeek is set to 3. Thus if we evaluate the switch statements, case 3 will be satisfied and then prints “Wednesday” on the console. Basically the case statement works this way, the variable inside the switch() declaration will be used to evaluate the cases. It would start from the first case, if the case is not satisfied, it will get omitted. The case will continue to evaluate until it reaches the condition case 3. Since the case is satisfied, a String “Wednesday” will get printed. Ideally, the code blocks after case 3 will get executed if not for the break statement that we have put after printing “Wednesday”. To illustrate this, let’s modify the above example removing the break keyword.

package com.javatutorial.example;


/*
 * This is demo program 
 * for case statement
 */

public class CaseDayOfWeekDemo {

	public static void main(String[] args) {
		
		
		int dayOfWeek = 3;
		switch(dayOfWeek){
		case 1: 
			System.out.println("Monday");

		case 2: 
			System.out.println("Tuesday");

		case 3: 
			System.out.println("Wednesday");

		case 4: 
			System.out.println("Thurday");

		case 5: 
			System.out.println("Friday");

		case 6: 
			System.out.println("Saturday");

		case 7: 
			System.out.println("Sunday");

		}	

	}

}

What do you think will be the result if we run the above example?

Wednesday
Thurday
Friday
Saturday
Sunday

Did you see what happen in there? Once a case has been satisfied, all the succeeding cases are also satisfied not unless a break statement is used.

If you are in doubt of this behavior, just use break. Most of the time you will only need to print once, you don’t need this fall through behavior of switch statement.