![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Jan 2008
Posts: 15
Rep Power: 0
![]() |
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 )
62 {
63 grossSales = ( sales < 0.0 ) ? 0.0 : sales;
64 } |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Apr 2005
Posts: 1,826
Rep Power: 5
![]() |
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 false Is equal to: if (statement that will be true or false)
use value on left side
else
use value on right sideSo the code you posted: public void setGrossSales( double sales )
{
grossSales = ( sales < 0.0 ) ? 0.0 : sales;
}Is equivilent to: public void setGrossSales( double sales )
{
if (sales < 0.0)
grossSales = 0.0;
else
grossSales = sales;
}It's an easy way to prevent the number from being negative, in one line. |
|
|
|
|
|
#3 | |
|
Newbie
Join Date: Jan 2008
Posts: 15
Rep Power: 0
![]() |
Re: What does ? : do?
Quote:
|
|
|
|
|
|
|
#4 |
|
Hobbyist Programmer
|
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.
__________________
i dont know much about programming but i try to help |
|
|
|
|
|
#5 | |
|
Programming Guru
![]() Join Date: Apr 2005
Posts: 1,826
Rep Power: 5
![]() |
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) C Syntax (Toggle Plain Text)
With a conditional operator: C Syntax (Toggle Plain Text)
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. |
|
|
|
|
|
|
#6 |
|
Newbie
Join Date: Jan 2008
Posts: 15
Rep Power: 0
![]() |
Re: What does ? : do?
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|