Conditional Statements

There are 4 types of conditional statements in Java.

  1. if

  2. if-then

  3. if-then-else

  4. switch

Let’s see what are the key words used in these different types conditional statements.

  • IF
    • Keywords : if, else
    • int number = 10;

      if (number == 10) {
      System.out.println(“Number is 10”);
      } else {
      System.out.println(“Number is not 10”);
      }

  • IF-THEN
    • Keywords : if, else if
    • int number = 50;

      if (number >= 75) {
      System.out.println(“You have a high grade”);
      }
      else if (number >= 50) {
      System.out.println(“You have a normal grade”);
      }

  • IF-THEN-ELSE
    • Keywords : if, else if, else
    • int number = 49;

      if (number >= 75) {
      System.out.println(“You have a high grade”);
      }
      else if (number >= 50) {
      System.out.println(“You have a normal grade”);
      } else {
      System.out.println(“You are fail”);
      }

  • SWITCH
    • Keywords : switch, case, default, break
    • int value = 100;

      switch (value) {
      case 100 : System.out.println(“Number is 100”); break;
      case 200 : System.out.println(“Number is 200”); break;
      case 300 : System.out.println(“Number is 400”); break;
      case 500 : System.out.println(“Number is 500”); break;
      default : System.out.println(“Number cannot be found”); break;

    • The use of “break” keyword is not a must but it is better to use it because it keeps the program off from checking below cases if one of the cases satisfies the condition.
    • default is also not a must to use. It will run only of the above cases don’t match the switch.

These conditional statements can be used in any manner even with in same conditional statement. Those type of conditions are called Nested-Conditions.

For instance :

if ( number > 0 ) {
if ( number <= 100) {

if ( number >= 75) {

System.out.println(“You have an A grade”);

} else {

System.out.println(“Any other grade”);

}

} else {

System.out.println(“Number is greater than 100”);

}

} else {

System.out.println(“Number is less than 0”);

}

That’t it for conditional statements.

Thank You.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s