Selection Statement in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

In java, selection statements are also known as branching statements or conditional or decision-making statements. It is used to select part of a program to be executed based on condition. In this article, we will be learning about selection statements in java along with its types and uses.

What is a Selection Statement in Java?

These are statements that control programs in java. They are used for selecting a path of execution if a certain condition is met.

The Selection Statements in Java

Following are the types of selection statements in java:

if Statement

General format:

if-statement-syntax-and-execution

Example:

Output:

Explanation: if the test expression is true then the statement is executed else the statement is not executed.

if-else Statement

General format:

if-else-statement-syntax-and-execution

Example:

Output:

Explanation: if the test expression is true then the statement is executed else statement 2 is executed.

Nested if Statement

General format:

Example:

Output:

Explanation: In this, writing an if statement inside another if statement is called the next if statement. If the first condition is true, it will check for the second condition after which the inner block will be executed else not.

if- else if- else Statement

General format:

Example:

Output:

Explanation: if test expression1 is true then statement 1 is executed else if test expression2 is true then statement2 is executed else statement3 will be executed.

Switch Statement

General format:

switch-statement-syntax-and-flow-diagram

Example:

Output:

Explanation: if the value of the expression is matched with value 1, then the corresponding stmt sequence is executed. If not matched with value 1 then try with the next case value and so on. If none of the cases match then default stmt is executed. All cases should be unique. The expression must be of type byte, short, int, or char Each case value should be literal. Default is not compulsory and can be written anywhere.

Note:

  • single statement does not require { }
  • Block of statements require { }

Conclusion

  • Selection statements are also known as branching statements or conditional or decision-making statements. It is used to select part of a program to be executed based on condition.
  • The selection statements in Java
    • if statement
    • if-else statement
    • nested if statement
    • if-else if statement
    • switch statement
  • These are statements that control programs in java. They are used for selecting a path of execution if a certain condition is met.