0

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

Hello I have some problems understanding the fallowing code, could anyone help me get this?

private Comparable elementAt( BinaryNode t ) {
    return t == null ? null : t.element;
}

I don't understand what t == null ? null : t.element; means.

Community
  • 1
  • 1
Bogdan M.
  • 2,161
  • 6
  • 31
  • 53

3 Answers3

5

return t == null ? null : t.element; means

if (t==null)
  return null;
else
  return t.element;

see also http://en.wikipedia.org/wiki/%3F:#Java

gefei
  • 18,922
  • 9
  • 50
  • 67
3

It is a standard idiom that avoids a NullPointerException in case t is null. In that case, instead of dereferencing it to get the element, it just returns null.

Some people argue that this is a bad idiom because it only postpones the NPE, but, depending on the exact situation, it could be just what one needs.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

its a ternary operator (in this case checking for null), ternarys can be used instead of if/else statements

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311