Java if...else Statement

if-else statement is a conditional statement that allows you to control the flow of your program based on the result of a boolean expression. The basic syntax of an if-else statement is:

if (expression) {
  // code to be executed if the expression is true
} else {
  // code to be executed if the expression is false
}

The expression is a boolean expression that returns either true or false. If the expression evaluates to true, the code inside the if block will be executed, and if it evaluates to false, the code inside the else block will be executed. If the expression is false, only the code inside the else block will be executed.

Here's an example of using an if-else statement to check whether a given number is positive or negative:

int number = -10;

if (number >= 0) {
  System.out.println(number + " is a positive number.");
} else {
  System.out.println(number + " is a negative number.");
}

-10 is a negative number.

  • Nested if-else statements: You can have if-else statements nested inside other if-else statements, allowing you to handle more complex conditions. For example:

int number = 10;

if (number >= 0) {
  System.out.println(number + " is positive.");
  if (number % 2 == 0) {
    System.out.println(number + " is even.");
  } else {
    System.out.println(number + " is odd.");
  }
} else {
  System.out.println(number + " is negative.");
}

  • Chaining if-else statements: You can chain multiple if-else statements together to handle different cases. For example:

int score = 75;

if (score >= 90) {
  System.out.println("Grade: A");
} else if (score >= 80) {
  System.out.println("Grade: B");
} else if (score >= 70) {
  System.out.println("Grade: C");
} else {
  System.out.println("Grade: D");
}

  • Ternary operator: Java also has a shorthand for simple if-else statements known as the ternary operator ? :. It can be used as an alternative to an if-else statement. For example:
 
int number = 10;
String result = (number >= 0) ? number + " is positive." : number + " is negative.";
System.out.println(result);
Next Post Previous Post
No Comment
Add Comment
comment url