if
, else if
, and else
Statements in Java:*if
Statement:*The if
statement in Java is used for conditional branching. It allows you to execute a block of code if a specified condition is true.
if (condition) {
// Code to execute if the condition is true
}
*else if
Statement:*if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true and condition1 is false
} else {
// Code to execute if both condition1 and condition2 are false
}
You can have multiple else if
blocks to test multiple conditions in sequence.
*else
Statement:*if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
? :
):The ternary operator in Java takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false.
result = (condition) ? valueIfTrue : valueIfFalse;
Example:
int x = 5;
int y = 10;
int max = (x > y) ? x : y;
In this example, max
will be assigned the value of x
if x
is greater than y
, and the value of y
otherwise.
switch
Statement:The switch
statement allows you to execute different code blocks based on the value of an expression. It's a compact way to handle multiple conditions.
switch (expression) {
case value1: // Code for value1
break;
case value2: // Code for value2
break;
// Additional cases
default: // Default code
}
expression
is compared against different case
values.