Lesson 5 – Conditional Statements in Java Copy

Conditional statements are used for decision making in any programming language. Java supports three types of conditional statements:

  • If
  • If/else
  • Switch

If Statement

If statement is used when you want to execute a piece of code if the condition specified by the if statement returns true. For instance, if you want to say “hello, how are you Sir?” if the age of a person is greater than 50, you can use if statement as follows:

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

int age = 55;
System.out.println("Hello, how are you Sir?");

}
}

Here in the above code, since the value of age variable is 55 which is greater than 50, you will see the following message in the output:

Hello, how are you Sir?

Now, if you update the value of age variable to 40, the if condition will return false since 40 is not greater than 50, hence the statement inside the if block will not execute and you will not see anything in the output.

If/Else Statement

The if/else statement is used when you want to execute an alternate code block in case the if statement returns false. In the following example the age variable is set to 40. The if statement checks if the age is greater than 50, which returns false. Hence the code in the else block executes.

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

int age = 40;
if(age > 50)
{
System.out.println("Hello, how are you Sir?");
}
else
{
System.out.println("Hey, hows you buddy, you are younger than 50");
}

}
}

The output looks like this:

Hey, hows you buddy

Switch Statement

If you want to check a large number of conditions, multiple if/else statements can get complicated. In such conditions, you can use switch statement as shown below:

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

int age = 60;

switch (age) 
{
case 40:
System.out.println("You are 40 years old");
break;
case 60:
System.out.println("You are 60 years old");
break;
default:
System.out.println("Sorry I dont know your age");
}
}
}

In the above code, the switch statement checks two condition. If the age is 40, a message telling the user that he is 40 years old is printed on the console. Similarly, if the age is 60, a corresponding message is printed. If age is neither 60 nor 40, then the default switch statement executes which prints “Sorry I don’t know your age”. Since the age is 60 in the above code, you will see following output:

You are 60 years old

<h3>What’s Next</h3> In this lesson we studied about conditional statements. In the next lesson, we will start our discussion about iteration statements.