Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Code Compilation error if not used braces with if [duplicate]

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.

like image 222
VISHNU GARG Avatar asked Jan 30 '26 21:01

VISHNU GARG


1 Answers

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;
like image 177
Eran Avatar answered Feb 01 '26 12:02

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!