0

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

I am trying to read an implementation of a binary tree, and I ran across this one line of code:

if (...) {
   ...
} else {
    node = ( node.left != null ) ? node.left : node.right;    //this line
}

return node;

Can anyone tell me what this line means? My best guess is that it's a conditional statement of some kind.

Community
  • 1
  • 1

2 Answers2

9

It is called Conditional Operator.

In expression1 ? expression2: expression3, the expression1 returns a boolean value. If it is true then expression2 is evaluated, else expression3 is evaluated.

So in your code snippet: -

node = ( node.left != null ) ? node.left : node.right;

is equivalent to: -

if (node.left != null) {
    node = node.left;
} else {
    node = node.right;
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

This is known as the ternary operator, since in most languages it's the only operator which takes 3 arguments. It has the form:

a ? b : c

and evalutes to b if a is true, or c otherwise. It can be used almost anywhere, but most frequently it is used in assignment operations, since it becomes very difficult to read in more complex situations.

On a side note, "obfuscated" is not the right term here - that is meant for code which is deliberately rendered difficult to read. This might more accurately be called "obscure", although it is a common operator.

Chris Hayes
  • 11,471
  • 4
  • 32
  • 47