When I try the below code, it gives me an error
int a =1,b=2;
if(a < b)
int c = 10;
But if I do the same adding curly braces, it works fine
int a =1,b=2;
if(a < b)
{
int c = 10;
}
But I'm just curious as to why Java does not allow creating a variable inside an if-condition.
It's nothing about integers, it's just that you cannot have a declaration under an if
statement without brackets. Note that it would be totally pointless since it would mean the declaration would be local to the if
statement, which would also have a single instruction (it's the meaning of no brackets), which means this declaration would never be used.
To make it more "visual":
if (condition) instruction;
is equivalent to
if (condition) {
instruction;
}
so in your case
if(a < b) {
int c = 10;
}
is a pointless code since c
will never be used. Therefore, it makes no sense for Java to allow writing
if(a < b) int c = 10;
An if
statement with brackets will allow you any content in the block (even no content at all) but if you make a declaration withoutusing the declared variable you'll still get a warning.
Your int c = 10;
is supposed to be a block local variable. You can only have these inside, well, a block (or some control structures like for
), and these blocks are denoted by curlies. A naked int c = 10;
is not a block.
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.