Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java variable cannot be resolved inside an IF Statement?

Tags:

java

jsp

<%
    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!

like image 641
Mustapha Aoussar Avatar asked Feb 04 '26 23:02

Mustapha Aoussar


1 Answers

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";
like image 155
Suresh Atta Avatar answered Feb 07 '26 15:02

Suresh Atta