![]() |
What does ? : do?
I am unsure of what the ? : is doing in Java. Ive searched in Google I cannot find anything, I have forgotten which book I read it out of but heres an example of some code that involves it:
:
61 public void setGrossSales( double sales ) |
Re: What does ? : do?
A question mark is known as a "conditional operator". Essentially, it's a one line
if statement.http://www.google.ca/search?hl=en&q=...operator&meta= It evaluates the statement before the question mark. If it's true, the statement inherits the value of the left side of the colon. If the statement is false, it inherits the value on the right side of the colon. :
statement that will be true or false ? value on left side of colon if true : value on right side of colon if falseIs equal to: :
if (statement that will be true or false)So the code you posted: :
public void setGrossSales( double sales )Is equivilent to: :
public void setGrossSales( double sales )It's an easy way to prevent the number from being negative, in one line. |
Re: What does ? : do?
Quote:
|
Re: What does ? : do?
@namsu you don't have to quote his entire post to say thank you.
I hardly ever see the ? operator. Using if or if else looks better as in more human readable than ?. It's style to me. |
Re: What does ? : do?
Well there are instances where it becomes necessary in order to prevent repeating code, or adding new variables in to the scenario. I'll make something up to demonstrate this...
Quote:
(Switching to C Code now) :
With a conditional operator: :
Each has their drawbacks, but personally I'd go with the latter, for sake of not repeating code. It's easier to change the format of the output, and the input specifications. |
Re: What does ? : do?
Quote:
|
| All times are GMT -5. The time now is 3:51 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC