The Use And Understanding Of “?” Operators
Posted by Vaibhav Pandey
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.
About the Author: Vaibhav Pandey got offered employment from an Indian Multinational IT Company. He is 21 years old. He has a huge interest in Java programming and has liked it from his study days. Vaibhav loves to blog and share his experiences and thoughts. He now resides in Lucknow, a state capital in India. Check out his blog at http://javatutorialsworld.blogspot.com.
iEntry 10th Anniversary
Cloud Computing
Certification
Leave a Reply