Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Sun Oct 28, 2012 1:42 pm
by ETS User
Although this construct is correct :

Code: Select all

	boolean flag = true;
[b]	if(flag = false){
		System.out.println("1");[/b]
	}else if(flag){
		System.out.println("2");
	}else if(!flag){
		System.out.println("3");
	}else 	System.out.println("4");
it obviously has no sense as the System.out.println("1"); as well as all other code in this block will be never executed. Just a curious, is there any situation when it will be?

Re: About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Sun Oct 28, 2012 2:23 pm
by admin
No, you are right, it will not be executed. The question is trying to test you on the construct flag = false.

BTW, you will find code in real exam that doesn't make sense in real life but you are expected to decipher it and understand what it is trying to do.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Sun Feb 02, 2014 10:15 am
by devlam
I should say that the final else is unreachable code because there is an elsif flag and an elsif !flag before that last else.
Why does the compiler not signal this unreachable code?

Re: About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Sun Feb 02, 2014 10:10 pm
by admin
There is no elseif in java. So you should not consider else if as one statement. You need to group it like this:

Code: Select all

        if (flag = false) {
            System.out.println("1");
        } else {
            if (flag) {
                System.out.println("2");
            } else {
                if (!flag) {
                    System.out.println("3");
                } else {
                    System.out.println("4");
                }
            }
        }


Re: About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Fri Feb 07, 2014 7:44 am
by devlam
Yes ok. But my point was that the statement
System.out.println("4")
is unreachable code, because on if (!flag) the result will always be true, which is not detected by the compiler.

Re: About Question com.enthuware.ets.scjp.v6.2.363 :

Posted: Fri Feb 07, 2014 7:53 am
by admin
devlam wrote:Yes ok. But my point was that the statement
System.out.println("4")
is unreachable code, because on if (!flag) the result will always be true, which is not detected by the compiler.
1. flag is a variable. Compiler cannot assume its value even if it is evident by looking at the code. Compiler can only use the values of compile time constants to determine if the code is unreachable or not.
2. if statement is granted an exception by the language designers. Please read this: http://docs.oracle.com/javase/specs/jls ... #jls-14.21

HTH,
Paul.