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 (condition) {
// Code to be executed if the condition is true
}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:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}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:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if neither condition1 nor condition2 is true
}Example Code:
Here's an example demonstrating the use of if, else if, and else statements in Java:
public class ConditionExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
}
}Explanation:
int number = 10;: Declares and initializes a variablenumberwith the value 10.if (number > 0) { ... }: Checks ifnumberis 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 ifnumberis 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:
The number is positive.This output occurs because the value of number (10) is greater than 0, satisfying the first condition.
Last updated