Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java equivalent of JavaScript var a = b || c [duplicate]

Tags:

java

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?

like image 724
Philipp Werminghausen Avatar asked Oct 28 '15 13:10

Philipp Werminghausen


2 Answers

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().

like image 94
Konstantin Yovkov Avatar answered Nov 08 '22 23:11

Konstantin Yovkov


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.

like image 35
Tunaki Avatar answered Nov 08 '22 23:11

Tunaki