Conditional Statements In Java

Let’s see the following conditional statements

1. if statement
2. nested if statement
3. if-else statement
4. if-else-if statement
5. Switch Case Statement

if statement:

The if statement is the most basic of all the control flow statements. The if statement tells our program to execute a certain section of code only if a particular test evaluates to true.

Syntax:

Sample Program:

Nested if statement:

An if statement inside another the statement. If the outer if condition is true then the section of code under outer if condition would execute and it goes to the inner if condition. If inner if condition is true then the section of code under inner if condition would execute.

Syntax:

Sample Program:

if-else statement:

If a condition is true then the section of code under if would execute else the section of code under else would execute.

Syntax:

Sample Program:

if-else-if statement:

Sample Program:

Switch Case:

The switch statement in Java is a multi branch statement. We use this in Java when we have multiple options to select. It executes particular option based on the value of an expression.

Switch Case

Switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types such as Character, Byte, Short, and Integer.

Syntax:

Sample Program:

Switch Case without break statement:

Switch Case with break statement:

Switch Case With Break

Must Read: Java Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Leave a Comment

Share via
Copy link
Powered by Social Snap