Java, like all other programming languages, is equipped with specific statements that allow us to check a condition and execute certain parts of code depending on whether the condition is true or false. Such statements are called Conditional, and are a form of

Conditional Statement.

In Java, there are two forms of conditional statements:

  • the if-else statement, to choose between two alternatives;
  • the switch statement, to choose between multiple alternatives.

if-else Statement: The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. 

if…else (if-then-else) Statement: The if statement executes a certain section of code if the test expression is evaluated to true. The if statement can have optional else statement. Codes inside the body of else statement are executed if the test expression is false. 

if..else..if Statement: The if statements are executed from the top towards the bottom. As soon as the test expression is true, codes inside the body of that if statement is executed. Then, the control of program jumps outside if-else-if ladder. If all test expressions are false, codes inside the body of else is executed.

Nested if…else Statement: It’s possible to have if..else statements inside a if..else statement in Java. It’s called nested if…else statement. Here’s a program to find largest of 3 numbers:

The switch Statement: Unlike if-then and if-then-else statements, 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).



Leave a Reply