There are two pieces of code

The first:

if(5 > 3) { int a = 5; } 

And the second:

 if(5 > 3) int a = 5; 

The second gives an error. Java 1.7, Win7 x64. Explain please why the second gives an error?

  • one
    And what a mistake? - Rams666
  • error '.class' expected - dirtez
  • @ dirtez, @ VladD that's all true, but one "but" if without brackets it turns out there is no scope, so the declaration and then initialization does not work? - Kerins_Sataier
  • @Kerins_Sataier: Because in this case, if the code does not follow the if branch, what should be with the variable? Should it be available in the scope where the if , even if the execution went by else ? How should it be initialized in this case? Because Java developers did not find satisfactory answers to these questions, they did not allow this. - VladD 2:55
  • @VladD cool argument, thanks Vlad! - Kerins_Sataier

1 answer 1

To declare a variable, you need scope. In the second case it is not.

The compiler cannot place the variable a in the external scope, because if the if -thiste fails, the variable will not be initialized.

  • thank! how much about IFA knew, and this is something new :) - stackoverflow
  • You are welcome! - VladD
  • That is, not so ?: int a; if (5> 3) a = 5; - Kerins_Sataier
  • Kerins_Sataier: not-a: ideone.com/I6xLay - VladD
  • @VladD, thanks for the vivid examples on this occasion. However, I do not understand what the scope version of if with brackets and without with the same condition that gives true differs in scope. - Kerins_Sataier