Why compiler error when defining a variable if block without braces?
java, javac
Solution
Java doesn't let you define a variable in an if statement without curly braces, since it could never be used (since there can be no other line it could be referenced from - it will be out of scope and therefore unavailable as soon as you hit the next line.)
If you put curly braces around the if statement, it will compile fine:
public class Test {
public static void main(String[] args) {
if (true) {
int b = 0;
}
}
}
Problem
Why does Java compiler suggest grammar error in the following code? ``` 1 public class Test { 2 public static void main(String[] args) { 3 if (true) 4 int b = 0; 5 } 6 } Test.java:4: '.class' expected int b = 0; ^ Test.java:4: not a statement int b = 0; ^ Test.java:4: illegal start of expression int b = 0; ^ Test.java:4: ';' expected int b = 0; ^ 4 errors ```