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?
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With