6

I am trying to create a variable and assign a value (if it exists) else assign a default value (short hand, like var a = b || c; in JavaScript)

public Object a = b || new Object();

Is that possible?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Philipp Werminghausen
  • 1,142
  • 11
  • 29

2 Answers2

7

Probably the ternary operator will be useful:

Object a = b != null ? b : new Object();

If b is not null, then a will be assigned to b, otherwise it will be assigned to a new Object().

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
5

There is no direct equivalent.

The most simple way would be:

public Object a = b == null ? new Object() : b;

Note that with Java 8, if b were defined as Optional<Object> (if not, you can always turn it into an Optional using Optional.ofNullable(b)), you could use orElseGet and write:

public Object a = b.orElseGet(Object::new);

which mimics the JavaScript syntax.

Tunaki
  • 132,869
  • 46
  • 340
  • 423