0% completed
Conditional statements in Java are used to perform different actions based on different conditions. The simplest forms are the if statement and the if...else statement. These statements allow your program to execute code selectively depending on whether a condition is true or false.
The if
statement evaluates a boolean expression (a condition) and executes a block of code only if the condition is true. If the condition evaluates to false, the code block is skipped.
if (condition) { // Code to execute if condition is true }
true
or false
).{}
that execute if the condition is true.Below is an example that checks if a number is positive.
Explanation:
number > 0
is evaluated.10
is greater than 0
, the code inside the if
block is executed, and "The number is positive." is printed.The if...else
statement extends the basic if
statement by providing an alternative block of code to execute if the condition evaluates to false.
if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
if
block is executed.else
block is executed.Below is an example that checks if a number is positive or negative.
Explanation:
number > 0
is evaluated.-5
is not greater than 0
, the condition is false.else
block is executed, and "The number is negative or zero." is printed.This lesson covers the basics of conditional execution with the if
and if...else
statements. They form the foundation of decision-making in Java programs and allow your code to respond dynamically to different input conditions.
In subsequent lessons, we will explore nested if...else statements, the ternary operator, and the switch statement for more complex decision making.
.....
.....
.....