java

Conditional Statements


Summary of Conditional Statements

StatementPurposeUse Case Example
ifExecutes code if a condition is true.Check if a number is positive.
if-elseExecutes one block if true, another if false.Check if a number is positive or negative.
if-else-if ladderTests multiple conditions in sequence.Determine if a number is positive, negative, or zero.
Nested ifAdds further conditions within an if.Check if a number is positive and even/odd.
switchExecutes one block from many cases.Perform actions based on days of the week.
Ternary operatorShortens simple if-else.Assign a value based on whether a condition is true (e.g., positive or negative).

1. if Statement

The if statement is used to execute a block of code only if a specified condition is true.

Syntax

Example


2. if-else Statement

The if-else statement is used to execute one block of code if the condition is true and another block if the condition is false.

Syntax

Example


3. if-else-if Ladder

The if-else-if ladder is used when there are multiple conditions to check.

Syntax

Example


4. Nested if Statements

An if statement can be used inside another if statement to perform additional checks.

Syntax

Example


5. switch Statement

The switch statement is used to execute one block of code from many options based on the value of a variable or expression.

Syntax

Example

Key Points

  • Use the break statement to terminate a case. Without break, the program executes all subsequent cases (fall-through).
  • The default block is optional but executes if no case matches.

Comparison of if-else and switch

Featureif-elseswitch
Use CaseFor complex conditions or ranges.For discrete values.
Data TypesSupports all data types.Supports int, char, String, enum.
ReadabilityLess readable for multiple conditions.More readable for multiple discrete cases.

6. Conditional (Ternary) Operator

The conditional operator (? :) is a shorthand for if-else.

Syntax

Example


Leave a Reply

Your email address will not be published. Required fields are marked *