[post-views]
In this lesson, you will learn,
if-else statements.
condition ? expression1 : expression2;
Here, condition is a boolean expression.
If the condition evaluates to true, expression1 is evaluated and becomes the result of the operation. If condition is false, expression2 is evaluated and becomes the result.
Using the ternary operator to assign the greater of two numbers to a variable.
public class TernaryExample {
public static void main(String[] args) {
int a = 5, b = 10;
int max = (a > b) ? a : b;
System.out.println("The greater number is " + max);
}
}
Output
The greater number is 10
public class TernaryPrintExample {
public static void main(String[] args) {
int number = 3;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(number + " is " + result);
}
}
Output
3 is Odd
public class NestedTernaryExample {
public static void main(String[] args) {
int a = 10, b = 20, c = 15;
int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("The largest number is " + largest);
}
}
Output
The largest number is 20
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.