Page 1 of 1

About Question enthuware.ocajp.i.v8.2.908 :

Posted: Fri Jan 01, 2016 5:54 am
by rezebric
The correct answer is "It will not compile." not the "Exception at run time."

Re: About Question enthuware.ocajp.i.v8.2.908 :

Posted: Fri Jan 01, 2016 9:06 am
by admin
I see that "It will not compile" is indeed marked as the correct answer. Please let me know if you see something else.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.2.908 :

Posted: Sat Aug 21, 2021 1:09 am
by dev_khaled
Hi, thank you for the great work. There is a bit misleading term in the explanation:
Item 4. All case labels should be COMPILE TIME CONSTANTS. You cannot have variables as case labels.
The highlighted sentence is a bit misleading. As you can have final variables with values evaluated at compile time as a case labels.

Try the following code

Code: Select all

public class Main {
    public static void main(String args[]) {
        
        int full = Integer.parseInt("20");
        
        
        // Next line causes compilation error because half's value cannot be evaluated at compile time!
        // final int half = full/2;
        
        
        // Next line causes compilation error because half is not final!
        // int half = 10;
        
        
        // Next line works perfectly! A final variable with value evaluated at compile time!
        final int half = 5 * 2;
        
        
        switch(full/2){
            case half: System.out.println("Final variable can work with case label!");
        }
    }
}
or run it directly from https://www.online-java.com/p1Bs95m8Yt

Suggestion: add clarification to the 2nd sentence

4. All case labels should be COMPILE TIME CONSTANTS. By either being a Literal value. eg: 50 or a Final variable whose value is evaluated at compile time. eg: final int someLabel = 5 * 2

Thank you.

Re: About Question enthuware.ocajp.i.v8.2.908 :

Posted: Sat Aug 21, 2021 4:53 am
by admin
You are right.
Explanation has now been enhanced.
thank you for your feedback!