Page 1 of 1

About enthuware.ocajp.i.v8.2.1279

Posted: Mon Feb 26, 2018 3:48 am
by Lunarkiran
How come we know that JLS explicitly defines this as an exception to the rule for if(false) and not for while(false).....? :roll:

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Mon Feb 26, 2018 5:34 am
by admin
We know because it is written in the specification: https://docs.oracle.com/javase/specs/jl ... #jls-14.21
Scroll to the bottom of section 14.21.

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Wed Aug 29, 2018 3:27 pm
by Jerome
Hi admin!

I don't get it. You wrote:
Similarly, for( int i = 0; false; i++) x = 3; is also a compile time error because x= 3 is unreachable.
So

Code: Select all

for( int i = 0; i< 0; i++) x = 3;
is also a compile-time error, isn't it?

Thus only two of them will compile without any errors:

Code: Select all

if (false) { x=3; }
do{ x = 3; } while(false);
Cheers,
Jérôme

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Wed Aug 29, 2018 6:57 pm
by admin
What happened when you tried compiling for( int i = 0; i< 0; i++) x = 3;. ?

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Fri Aug 31, 2018 1:50 am
by Jerome
Hi,

ok I got it:
for( int i = 0; i< 0; i++) x = 3; => x is reachable with i<0
for( int i = 0; false; i++) x = 3; => x is never reachable, no matter the value of i

It was easy ;o)

Thanks for your support
Jérôme

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Thu May 09, 2019 10:07 pm
by vilasa
admin wrote:
Wed Aug 29, 2018 6:57 pm
What happened when you tried compiling for( int i = 0; i< 0; i++) x = 3;. ?
compiles fine.But x is unreachable .Because when I tried to print x ,it was 0 . As per logic explained in JLS this should give compile error

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Thu May 09, 2019 10:25 pm
by admin
No, which part of JLS are your referring to? Please go through the replies above.

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Fri May 10, 2019 5:13 pm
by vilasa
I understand now. Thank you .

Re: About enthuware.ocajp.i.v8.2.1279

Posted: Mon Jan 17, 2022 12:43 pm
by tangjm
Jerome wrote:
Fri Aug 31, 2018 1:50 am
Hi,

ok I got it:
for( int i = 0; i< 0; i++) x = 3; => x is reachable with i<0
for( int i = 0; false; i++) x = 3; => x is never reachable, no matter the value of i

It was easy ;o)

Thanks for your support
Jérôme
Yeah, the key thing to note is the use of the term 'constant expression' in section 14.21 of the JLS.

'The contained statement is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.'

To clarify, 'i < 0' is not a constant expression whereas 'false' is a constant expression. Hence, the former 'for' loop is reachable and compiles but the latter is unreachable and fails to compile.