简体   繁体   中英

Why compiler error when defining a variable if block without braces?

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

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

You need to add curly braces while defining a variable inside if .

public static void main(String[] args) {
    if (true) {
        int b = 0;
    }

}

Since when you write without curly braces

if()
//something

Only that line executes and in that place if you are trying to define a variable that doesn't make any sense.

And the compiler smart enough to complain :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM