The " ? " Operator
Java includes a special Three-way(Ternary) operator that can replace certain types of if-then-else statements.These statements include assignment when certain conditions are fulfilled.This operator is " ? ".The working of " ? " operator is similar as in C,C++ and C#.The " ? " operator at first look might seem confusing but it is extremely useful in particular conditions when mastered.
General Syntax :-
expression 1 ? expression 2 : expression 3
Here expression 1 can be any expression that evaluates to a Boolean value.If expression 1 is true then expression 2 is evaluated else expression 3 is evaluated.Both the expressions expression 1 and expression 2 must have a return type,they can never be void.Make it more clear by understanding below example.
Example:-
public class optest
{
public static void main(String a[])
{
int ratio=0,num=20,denom=10;
/* The " ? " operator assignes 0 if condition denom==0 is true else it assigns num/denom to ratio if condituion is false*/
ratio=denom==0?0:num/denom;
System.out.println("The ratio is "+ratio);
}
}
Output:-
The ratio is 2
Explanation:-When Java evaluates this assignment expression ,it first looks at the expression to the left of the question mark.If denom equals to zero then expression 2 between ? and : is evaluated else last expression is evaluated.The resultant is then assigned to the ratio variable used in expression 1.
Suggested Reading:-
Arithmetic Operators
Conditional Operators
Logical Operators
Assignment Operators
Relational Operators
Bitwise Logical Operators
Operators Practice Questions
Read more...
General Syntax :-
expression 1 ? expression 2 : expression 3
Here expression 1 can be any expression that evaluates to a Boolean value.If expression 1 is true then expression 2 is evaluated else expression 3 is evaluated.Both the expressions expression 1 and expression 2 must have a return type,they can never be void.Make it more clear by understanding below example.
Example:-
public class optest
{
public static void main(String a[])
{
int ratio=0,num=20,denom=10;
/* The " ? " operator assignes 0 if condition denom==0 is true else it assigns num/denom to ratio if condituion is false*/
ratio=denom==0?0:num/denom;
System.out.println("The ratio is "+ratio);
}
}
Output:-
The ratio is 2
Explanation:-When Java evaluates this assignment expression ,it first looks at the expression to the left of the question mark.If denom equals to zero then expression 2 between ? and : is evaluated else last expression is evaluated.The resultant is then assigned to the ratio variable used in expression 1.
Suggested Reading:-
Arithmetic Operators
Conditional Operators
Logical Operators
Assignment Operators
Relational Operators
Bitwise Logical Operators
Operators Practice Questions


















