Ternary Operators In Java Example
Chapter:
Operators
Last Updated:
15-07-2016 14:07:16 UTC
Program:
/* ............... START ............... */
public class JavaTernaryOperatorExample {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
/* ............... END ............... */
Output
Absolute value of 10 is 10
Absolute value of -10 is 10
Notes:
-
Ternary Operators commonly referred to as the conditional operator
- eg : minVal = (a < b) ? a : b
- Java ternary operator let's you assign a value to a variable based on a boolean expression either a boolean field, or a statement that evaluates to a boolean result.
Tags
Ternary Operators, Java