If Else In Java

https‮al.www//:‬utturi.com
If Else In Java

In Java, you can use the if-else statement to execute different blocks of code based on a condition. The if-else statement has the following syntax:

if (condition) {
  // code to execute if the condition is true
} else {
  // code to execute if the condition is false
}

In this example, the condition is a boolean expression that is evaluated to either true or false. If the condition is true, the code inside the first set of curly braces is executed. If the condition is false, the code inside the second set of curly braces is executed.

Here is an example of how to use the if-else statement to check if a number is positive or negative:

int number = 10;

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

In this example, the condition number > 0 is evaluated to true, so the code inside the first set of curly braces is executed and the message "The number is positive." is printed to the console.

You can also use the if-else statement to check multiple conditions by using the else if clause, like this:

int number = 10;

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

In this example, the code will check if the number is positive, then if it is 0, and finally if it is negative. Only the code inside the first block of curly braces that is associated with a true condition will be executed.

Note that the if-else statement is a powerful tool for controlling the flow of your program based on different conditions. It is important to carefully consider the conditions and actions in your if-else statements to ensure that your code is correct and easy to understand.

Created Time:2017-11-01 22:29:43  Author:lautturi