Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Wed Aug 06, 2014 9:05 am
by vchhang
I can't seem to find anywhere in the JLS that states the default statement must be the last label.

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Wed Aug 06, 2014 10:18 am
by admin
vchhang wrote:I can't seem to find anywhere in the JLS that states the default statement must be the last label.
Because it can be anywhere. That is why it is not a correct option.

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Thu Feb 11, 2016 2:55 pm
by yegomosc
Hi,

Code: Select all

 public static void main(String[] args) {
        char a = 'a';
        byte b = (byte) a;
    }
the above code piece of code had to contains expliciite casting to byte

but in the Line //1 it was not required (Why?? :shock: )

Code: Select all

void test(byte x) {
        switch (x) {
            case 'a':   // 1
            case 256:   // 2
            case 0:     // 3
            default:   // 4
            case 80:    // 5
        }
    }
I couldn't find the explanation, why it is possible that it worked?

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Thu Feb 11, 2016 8:15 pm
by admin
In Java, char data type is actually a numeric type that can have any value between 0 to 2^16-1. It is interpreted by the JVM as a unicode character. Therefore, 'a' is actually nothing but same as its ascii value 96.

Now, since 96 can perfectly fit within a byte, the case statement above works. But your next case 256 will not compile because 256 will not fit in a byte. (A byte can store numbers from -128 to 127 only).

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Mon Feb 15, 2016 3:01 pm
by NickWoodward
don't mean to butt in, but i think he or she is asking why the variable char a needs a cast, but 'a' does not.

pretty sure it's because the compiler knows what 'a' is at compile time, it's a literal. it knows that 'a' fits in a byte.

char a = 'a';
byte b = (byte) a;

however char a could've been changed for all the compiler knows - the compiler doesn't run code - so it cannot be sure that char a can still fit into the scope or range of a byte.

i'm sure someone else can explain it better than i have, but i think that's the general idea.

nick

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Thu Mar 07, 2024 10:34 am
by likejudo
When I try to cast it to a byte, I get error

java: duplicate case label


I don't understand why.

Code: Select all

    void test(byte x){
        switch(x){
            case 'a':   // 1
            case (byte) 256:   // 2
            case 0:     // 3
            default :   // 4
            case 80:    // 5
        }
    }

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Thu Mar 07, 2024 8:58 pm
by admin
(byte) 256 is 0.

Re: About Question enthuware.ocajp.i.v7.2.1045 :

Posted: Thu Mar 07, 2024 10:08 pm
by likejudo
thanks!

Code: Select all

        System.out.println((byte) 256);
0