Why Java variable cannot be resolved inside an IF Statement?

java, jsp

Solution

You restricted the scope of the the variable `cssClassContainer`

You might want

<%
    String cssClassContainer=""; // or null
    if (group.isControlPanel()) {
         cssClassContainer = "container";
    } else {
         cssClassContainer = "container-fluid";
    }
%>

What happened with your code now is the scope of variable `cssClassContainer` restricted to `{}`

Out side of that you cannot access.

The above condition can replace by (Skeets magic :)) ,

 String cssClassContainer = group.isControlPanel()? "container" : "container-fluid";

Problem

``` <% if (group.isControlPanel()) { String cssClassContainer = "container"; } else { String cssClassContainer = "container-fluid"; } %> ``` I get a compile error when I define a variable inside If Statement: `An error occurred at line: 40 in the jsp file: /page.jsp__cssClassContainer cannot be resolved to a variable.` When I remove If Statement I don't get any error: ``` <% String cssClassContainer = "container"; %> ``` Why? Any help is appreciated! Thank you so much!

Original source