0
ltVal = node.left  != null ? node.left.height  : 0;

I think this is written in Java, can anyone explain what this means? Can't understand this shorthand notation

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
ZeferiniX
  • 500
  • 5
  • 18

1 Answers1

2

It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format

General Syntax :

boolean expression ? value1 : value2

your example:

ltVal = node.left  != null ? node.left.height  : 0;

as same as

  if( node.left != null)
       itVal = node.left.height
  else
       itval = 0;
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • Thanks for clearing things, I get confused most of the times if I don't see any parenthesis xD Didn't realize it was a ternary operator being assigned to "ltVal" until someone explained xD – ZeferiniX Sep 21 '14 at 06:32
  • @ZeferiniX do not worry you will get use to it. you should get to use this kind of coding cuz lambda has already arrived in Java. :) – Kick Buttowski Sep 21 '14 at 06:33
  • Is it a good practice not to put parenthesis? Most examples I find that uses ternary operators don't have parenthesis @_@ Could've understand this better if it was ltVal = ( (node.left != null) ? node.left.height : 0 ); – ZeferiniX Sep 21 '14 at 06:38
  • @ZeferiniX I think using parenthesis is up to how much experience you have in programming :) – Kick Buttowski Sep 21 '14 at 06:41