Condition
Conditions in Java are used to make decisions in a program. They allow you to execute different code blocks based on whether a specified condition evaluates to true or false. Conditions are typically implemented using if
statements, else
statements, and else if
statements.
if
Statement:
if
Statement:The if
statement is used to execute a block of code only if a specified condition is true. Here's the syntax:
if-else
Statement:
if-else
Statement:The if-else
statement allows you to specify two blocks of code: one to be executed if the condition is true, and another if the condition is false. Here's the syntax:
else if
Statement:
else if
Statement:The else if
statement allows you to specify multiple conditions. It is used in conjunction with if
and else
statements to test multiple conditions. Here's the syntax:
Example Code:
Here's an example demonstrating the use of if
, else if
, and else
statements in Java:
Explanation:
int number = 10;
: Declares and initializes a variablenumber
with the value 10.if (number > 0) { ... }
: Checks ifnumber
is greater than 0. If true, the code inside the block is executed, printing "The number is positive."else if (number < 0) { ... }
: If the first condition is false, this statement checks ifnumber
is less than 0. If true, it prints "The number is negative."else { ... }
: If both previous conditions are false, this block is executed, printing "The number is zero."
When you run this Java program, it will output:
This output occurs because the value of number
(10) is greater than 0, satisfying the first condition.
Last updated