java
  1. java-if-else

Java If-else Page

Syntax

if(condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}

Example

Here's an example of using if-else in Java to determine if a number is even or odd:

int num = 12;
if(num % 2 == 0) {
  System.out.println(num + " is even");
} else {
  System.out.println(num + " is odd");
}

Output

If the value of num is 12, the output will be: 12 is even.

Explanation

The if-else statement in Java is used to execute a block of code if a condition is true, and another block of code if the condition is false. In the example above, the condition num % 2 == 0 checks if the value of num is divisible by 2 with no remainder, which means it's an even number. If the condition is true, the first block of code is executed (print "num is even"), and if it's false, the second block of code is executed (print "num is odd").

Use

If-else statements are commonly used in programming to execute different blocks of code based on certain conditions. They can be used for a wide range of applications, from simple conditional statements like the example above, to more complex decision-making processes.

Important Points

  • The condition in an if-else statement must evaluate to a boolean value (true or false).
  • The code within the curly braces will only be executed if the condition is true (for the if statement) or false (for the else statement).
  • You can have multiple else-if statements (in addition to the if and else statements) to execute blocks of code based on multiple conditions.

Summary

The if-else statement in Java is commonly used to execute different blocks of code based on certain conditions. The condition in the statement must evaluate to a boolean value, and the code within the curly braces will only be executed if the condition is true (for the if statement) or false (for the else statement). It's a powerful tool for conditional programming and can be used in a wide variety of applications.

Published on: