0

I have some issues understanding why one way of declaring and initalising a local variable is allowed and one isn't.

For example, this doesn't compile:

if ("b" == "b")
  int a = 1;

Whereas, the following examples compile:

if ("b" == "b") {
  int a = 1;
}

and

int a;
if ("b" == "b")
  a = 1;

Can you please help me with this?

a should be in scope even though I am not using the {,} brakets. If it helps, the error suggested by the compiler is: error: not a statement - thus, it doesn't recognise int as a statement.

bgguna
  • 19
  • 5
  • Check [here](http://stackoverflow.com/questions/31230722/java-variable-declaration-not-allowed-here) – sam Oct 20 '15 at 13:53
  • @sam2090 I don't consider this a duplicate as the question you suggested is different in terms of the received error and solution provided to the problem. I will edit the question to cover these details. – bgguna Oct 20 '15 at 14:22
  • 1
    The accepted answer in the duplicate states: _Of note is that declaration statements (e.g. int a; or int a = 10;) are missing from that list, thus you get a compilation error._ It's as simple as that. The Java Language Specification disallows it. – Sotirios Delimanolis Oct 20 '15 at 14:31
  • 1
    In simple words, JLS specs doesn't allow declaring variables under `if` without `braces` and one of the answer in the link I posted provides link to the doc. :) – sam Oct 20 '15 at 14:48
  • @sam2090 Thank you for your answer. I just didn't understand why I received the compilation error in the first place (as the declaration statement is possible with `{` and I thought this should be in scope). Apologies for asking a question similar to others' :-). – bgguna Oct 20 '15 at 14:55

0 Answers0