Java - Short Hand If...Else
Short Hand If...Else is a concise way of writing if...else statements. It allows you to write an if...else statement in a single line of code.
The syntax of Short Hand If...Else is as follows:
(condition) ? expressionTrue : expressionFalse;
Here, condition is the expression that is evaluated, expressionTrue is the expression that is returned if the condition is true, and expressionFalse is the expression that is returned if the condition is false.
For example, consider the following code using a regular if...else statement:
int num = 5;
if(num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Negative number");
}
This code can be simplified using Short Hand If...Else as follows:
int num = 5;
String result = (num > 0) ? "Positive number" : "Negative number";
System.out.println(result);
Here, result is assigned the value "Positive number" if num is greater than 0, and "Negative number" if num is less than or equal to 0. The value of result is then printed to the console using System.out.println().
int x = 10, y = 20;
String result = (x > y) ? "x is greater than y" : "y is greater than or equal to x";
System.out.println(result);
In this example, we declare two variables x and y, and then we use Short Hand If...Else to check whether x is greater than y. If the condition is true, we assign the string "x is greater than y" to the result variable; otherwise, we assign the string "y is greater than or equal to x". Finally, we print out the result variable. In this example, the result variable will be assigned the string "y is greater than or equal to x" because x is not greater than y.
int x = 5, y = 10;
String result = (x > 0 && y > 0) ? "Both x and y are positive" : "Either x or y is not positive";
System.out.println(result);
In this example, we declare two variables x and y, and then we use Short Hand If...Else with the logical operator && to check whether both x and y are positive. If the condition is true, we assign the string "Both x and y are positive" to the result variable; otherwise, we assign the string "Either x or y is not positive". Finally, we print out the result variable. In this example, the result variable will be assigned the string "Both x and y are positive" because both x and y are positive (i.e., greater than 0).