Monday, December 28, 2009

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

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP