1

Possible Duplicate:
What is the Java ?: operator called and what does it do?

In some code a ? is used to perform a mathematical equation.

What is it and how do you use it? Is it possible to provide an example and the reason for the final answer of an equation?

int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;
Community
  • 1
  • 1
Akyl
  • 349
  • 1
  • 4
  • 21

8 Answers8

11

Basically is the ternary operator:

String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!"; 

if isHappy, then "I'm Happy!". "I'm Sad!" otherwise.

Andres Olarte
  • 4,380
  • 3
  • 24
  • 45
4

I presume you mean something like x = () ? y : z; notation? If that's the case, then the expression within the parentheses is evaluated as a boolean, if true x = y otherwise x = z

posdef
  • 6,498
  • 11
  • 46
  • 94
4
int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;

Means that the top variable will contain the value of getChildAt(0).getTop() if the count variable is greater than 0, else it will equal to 0

Alex
  • 25,147
  • 6
  • 59
  • 55
2

My guess is you are referring to the ternary operator, which is used like this:

<some condition> ? <some value> : <some other value>;

For example:

int max = a > b ? a : b;

It's a shorthand for an if and is equivalent to:

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

but allows a one-line result in code.

When used well, it can make code much more clear due to its terseness. However caution is advised if the line becomes too long or complicated: The code only remains readable when the terms are brief.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

The ? in an evaluative expression is called the ternary operator. It is essentially short-hand for an if() ... else block.

http://en.wikipedia.org/wiki/%3F:

asteri
  • 11,402
  • 13
  • 60
  • 84
0

I assume you're referring to the ternary operator. It's shorthand for certain kinds of if statements. Where you're making an assignment, like:

int dozen = (bakersDozen) ? 13 : 12;

Assuming bakersDozen is true, then dozen will be 13. If it's false, it will be 12.

thegrinner
  • 11,546
  • 5
  • 41
  • 64
0
int result = (a > b) ? 1 : 0;

is the same than

int result;
if (a > b)
  result = 1;
else
  result = 0;
Sergio
  • 640
  • 6
  • 23
0

? Is usually a ternary (or tertiary) operator. So let's explain what it is doing.

myValue = (a = b) ? 1 : 0;

The first part is your condition. "Does a equal b?"

The second part is the true response.

The third part is the false response.

So if a is equal to b, myValue will be 1. If a is not equal to b, myValue will be 0.

See http://en.wikipedia.org/wiki/Ternary_operation

J. Tanner
  • 575
  • 2
  • 10