2

Why does the following code give a compilation error?

if (true)
    int p=10;

The following similar code works if I use block:

if (true) {
    int p=10;
}

I am using Eclipse IDE. Please let me know the exact reason why we can't do the first one.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • If you declare variable in if statement without braces then it cannot referenced in code i.e. is unreachable.so it's useless to declare such variable.Compiler is smart enough identify such situation and throws compiler error to prevent it.So You need to have `{}` around variable declaration. Check this for more info.http://stackoverflow.com/questions/23081428/java-declare-a-variable-in-an-if-statement-without-curly-braces – Flying_Machine Oct 30 '14 at 07:13

1 Answers1

9

You can't declare a variable without a scope. Therefore, you need the braces in order to declare p.

If p was declared outside the if statement, you could have assigned a value to it in the if statement without using braces.

int p;
if (true)
     p = 10;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    But By default it is in scope of If statement....So why compiler doesn't understand the meaning.. Because while excuting code it works fine except for intialaztion – VISHNU GARG Oct 30 '14 at 07:02
  • 2
    Because if statements don't create a scope. Braces do. – JB Nizet Oct 30 '14 at 07:04
  • @VISHNUGARG It's not a question of the compiler "understanding" anything here - requiring local variables being immediately in a block (or braces) is standards comforming, see JLS 14.4 – jdphenix Oct 30 '14 at 07:05
  • 3
    Perhaps that's how the compiler would have been written. By default without braces, the scope is just one line. So what's the point of declaring any variable **for just one line**? Isn't it a smarter strategy to throw a compilation error... hey! you might be wanting to do something else, did you forget the braces ? – Lokesh Oct 30 '14 at 07:06
  • Thanks for writing I have gone through the Oracle doc as well, Its clearly written over there...@ Lokesh I am validating different cases and compiler behavior on that I know Its a bad code practise – VISHNU GARG Oct 30 '14 at 07:11