Enabling Non-Ints in Java

I had problems figuring out the internal operation of the switches in Java. They told me that for all primitives, the value is raised to a whole.

However, in the following example, I am testing a byte variable, and any case greater than 127 will not compile:

byte k = 5; switch(k){ case 128: //fails to compile, possible loss of precision 

I understand that this is a mistake, and I have no problem with this. My question is:
How does the JVM track that it includes a byte if it takes a value of "k" and advances it to an integer before testing each case?

+4
source share
6 answers

The problem is that it does not advance the value of k, it is trying to take a case statement (128-digit integer) and assign it to a byte. Since 128 is greater than 1 byte (7 bits + sign bit), compilation is not performed.

for instance

 byte k = 128; 

also does not compile. See Java Language Specification

+3
source

The switch not limited to int . The Java Language Specification (JLS), section 14.11, The Switch Statement , contains

The type of the expression must be char, byte, short, int, Character, Byte, Short, Integer or enum, or a compile-time error.

Therefore, your byte does not advance to int . JLS goes on to say that what you do will cause a compile-time error:

Each case constant expression associated with a switch statement must be assigned to an Expression type of expression.

... since 128 is not assigned a byte .

+9
source

It does not compile because:

Type mismatch: cannot convert from int to byte

This is obvious because your k is of type byte , and the letter 128 is int in accordance with the Java rule.

If you change the case statement:

 case (byte) 128: 

then it will compile without errors.

+2
source

You just need to click byte :

 switch(k) { case (byte) 128: } 

That's fine - the problem was that there was no implicit conversion from 128 to byte literal. You get the same problem with a simple assignment:

 // Invalid byte a = 128; // Valid byte b = (byte) 128; 

The value of b will actually be -128, since 128 is outside the Java byte range, but the bit pattern is correct, so in many cases this is what you want; it is also a value that will hit the case specified in the switch statement above.

+1
source

The Java Spec says:

Each constant case expression associated with the switch statement must be assigned (section 5.2) to the type of Expression expression.

JVM Spec says the type is being promoted, but it's different (not compile time).

+1
source
Byte

has a size from -128 to 127. when you pass a byte as a switch enclosure, accuracy is lost and allocates the time required for the compilation byte, it detects an int error. byte (128) will solve the problem.

0
source

Source: https://habr.com/ru/post/1388667/


All Articles