Initialising Java String literal giving error

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??

enter image description here

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128730&siteId=1