Java has a ternary operator that acts as an abbreviated form of an if-then-else statement.
Conditional operator and type cast operator
Operator | Meaning |
a = boolean ? b : a | Conditional operator - The first operand - boolean - is a boolean variable or expression. First this boolean operand is evaluated. If it is true then the second operator evaluated and a is set to that value. If the boolean operator is false, then the third operand is evaluated and a is set to that value. |
(primitive type) | Type cast - To assign a value of one primitive numeric type a more narrow type, e.g. long to int, an explicit cast operation is required, e.g. long a = 5; int b = (int)a; |
Syntax of Conditional Operator and Type Cast Operator
expr1 ? expr2 : expr3
expr1 can be any boolean expression. If expr1 is true, then expr2 is evaluated else expr3 is evaluated. Ternary operator returns either the value of expr2 or expr3.
Note that type of expr2 and expr3 must be same.
varName2 = (typeCastOptr) varName1;
varName2 is a variable of type specified at typeCastOptr.
typeCastOptr is a data type in which varName1 need to convert.
varName1 is a variable which you need to type cast.
Example of Conditional Operator and Type Cast Operator
Example 1 : Program to compare 2 numbers using Conditional Operator i.e ? : and type cast variable from int to float using Type Cast Operator
class CndTyCastOptrDemo
{
public static void main(String args[])
{
int i = 10;
float f = 15.0f;
System.out.println("Greater Number from i and f is " + (f>i)? "f having value " + f: "i having value " + i);
f = (float)i/2;
System.out.println("Value of variable f is " + f);
}
}
Output
Greater Number from i and f is f having value 15
Value of variable f is 5