Java if-else Statement

The if-else statement is an extension of the if statement that allows you to specify two different code blocks to be executed depending on the result of the condition. The else clause is optional, so it is possible to use an if statement without an else clause. It is also possible to nest if-else statements, which allows you to test multiple conditions and execute different code blocks depending on the results.

Java if-else

The if-else statement is a control structure that allows you to execute different code blocks depending on the result of a boolean condition. It has the following syntax:

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

The if part of the if-else statement specifies a condition to be tested, and the code block that follows it will be executed if the condition is true. The else part of the if-else statement specifies a code block to be executed if the condition is false.

Here is an example of an if-else statement that checks if a number is positive or negative:

int x = 10;
if (x > 0) {
  System.out.println("x is positive");
} else {
  System.out.println("x is negative");
}

This code will output “x is positive” because the condition x > 0 is true.

Java if-else Example

Here are some examples of the if-else statement in Java:

Checks if a number is positive or negative

int x = 10;
if (x > 0) {
  System.out.println("x is positive");
} else {
  System.out.println("x is negative");
}

This code will output “x is positive” because the condition x > 0 is true.

Checks if a number is even or odd

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

This code will output “x is odd” because the condition x % 2 == 0 is false (the remainder of x divided by 2 is not equal to 0).

Check if a character is a vowel or a consonant

char ch = 'a';
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
  System.out.println("ch is a vowel");
} else {
  System.out.println("ch is a consonant");
}

This code will output “ch is a vowel” because the condition ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' is true (ch is equal to 'a').

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *