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 and most uses conditional 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 an optional else statement. Codes inside the body of else statements 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 the statement is executed. Then, the control of the program jumps outside the if-else-if ladder. If all test expressions are false, codes inside the body of else are executed.

 

Nested if…else Statement

It’s possible to have if..else statements inside an if..else statement in Java. It’s called a 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). The switch statement is most uses conditional statements like if-else.

 

Ref: docs.oracle.com

Conditional Statements in Java

Leave a Comment