-1

Hello guys very simple question for you. I just dont know how to google this, we use this in our framework and i want learn more about it but i dont know what is it. can you please help?This is simplest example.Any lead how can i google it will be good answer for me.

 myVariable != null ? myVariable : 5
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Martin Ma
  • 125
  • 1
  • 13
  • ternary operator – drum Jul 01 '22 at 16:16
  • That is a conditional `?:` expression, sometimes imprecisely called the ternary expression (it _is_ a ternary expression, but it's just 1 kind of ternary expression). It's described in https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html ("Another conditional operator is `?:`") – Andy Turner Jul 01 '22 at 16:16
  • It reads a bit easier if you add spaces and parenthesis: `(myVariable != null) ? myVariable : 5` – markspace Jul 01 '22 at 16:18
  • There's several bits of syntax going on, so which part are you asking about? Because this code looks incomplete: it doesn't "result" in anything, even if it does something on its own (it will evaluate a ternary, and the result will be uselessly thrown away in the code you're showing) – Mike 'Pomax' Kamermans Jul 01 '22 at 16:23

1 Answers1

1

Ternary operator. If myVariable does not equal null, the expression evaluates to myVariable. Otherwise, 5*.

Equivalent to:

myVariable == null ? 5 : myVariable

*Since myVariable is compared to null, this is clearly an object rather than a primitive, so the entire expression is expected to return an object, so technically this returns Integer.valueOf(5).

Chris
  • 26,361
  • 5
  • 21
  • 42