Java From Beginner To Advanced

0% completed

Previous
Next
Java if...else Statement

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

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.

Syntax

if (condition) { // Code to execute if condition is true }
  • condition: An expression that returns a boolean value (true or false).
  • Code block: One or more statements enclosed in curly braces {} that execute if the condition is true.

How It Works

  • The condition is evaluated.
  • If the condition is true, the statements inside the block are executed.
  • If the condition is false, the block is skipped.

Example: Simple if Statement

Below is an example that checks if a number is positive.

Java
Java

. . . .

Explanation:

  • The condition number > 0 is evaluated.
  • Since 10 is greater than 0, the code inside the if block is executed, and "The number is positive." is printed.

The if...else Statement

The if...else statement extends the basic if statement by providing an alternative block of code to execute if the condition evaluates to false.

Syntax

if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
  • condition: An expression that returns a boolean value.
  • If block: Executes when the condition is true.
  • Else block: Executes when the condition is false.

How It Works

Image
  • The condition is evaluated.
  • If the condition is true, the code in the if block is executed.
  • If the condition is false, the code in the else block is executed.

Example: Using if...else Statement

Below is an example that checks if a number is positive or negative.

Java
Java

. . . .

Explanation:

  • The condition number > 0 is evaluated.
  • Since -5 is not greater than 0, the condition is false.
  • Consequently, the code inside the 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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next