shishir :
This java string literal initializing giving error when the code to initialize is within checking if par1 has a value or not. I am not sure whether I am doing or its some other issue??
public class optionalFields {
public static void main(String args[])
{
optional_func(Optional.of(true));
}
public static void optional_func(Optional<Boolean> par1)
{
if(par1.isPresent())
String s = "test";
System.out.println(s);
}
}
Eran :
It should be:
if (par1.isPresent()) {
String s = "test";
System.out.println(s);
}
You cannot declare a variable inside an if
statement unless you put the declaration in a block. Besides, since you are printing s
, the println
statement should also be inside the block of the if
statement.
If you want to print s
even if the condition is false, it should be:
String s = null;
if (par1.isPresent())
s = "test";
System.out.println(s);