ZuhriUtama

Null Safe Operator on Java

i'm familiar with php null safe operator using "?" to prevent error when the variable or method return null value. how to get the same result on java

it's easy since PHP 8 to prevent error when code trying to access value from variable or method that has null value and set default value if the result is null. you can use ? on your code like this

$b = $a ?? 0;

it will set $b as 0 instead null. you can also use when call method from class.

$b = $a?->val();

it will set $b as null instead throwing error $a is null when call method $val.

and then i need on java. i found there is java.util.Optional class to use that has same result.

you can code like this

use java.util.Optional;

int b = Optional.ofNullable(a).orElse(0);

good luck!

05 Jun 2024 14:20 36 0

Komentar

Belum ada komentar, jadilah yang pertama

Kirim Komentar