Primitive type casting in java (disconcerting examples)

I've read most of the threads on this site concerning typecasting (please do not link me to any more or mark this as a duplicate), and would like an explanation on some of these specific cases.

1)

char x='a';
char y = 'b';

In this case, we are not allowed to do

char z = x + y; \\case 1a

But we can do

char z='a'+'b'; \\ case 1b

I read on this site that the addition of two chars results in an int, and that is why we cannot do 1a, but if so, why can we do 1b.

2)

Why is this allowed

byte byteVar = 42;

The literal 42 is an int, so why are we allowed to store it in a byte without casting even though 42 is in the range of byte. If this can be done, why can't 1a be done.

3) The following returns true

System.out.println(6.0000000000000000000000000000000001 == 6.0);

The RHS is treated as a literal double. I'm guessing that the LHS is treated as a literal double as well, but it definitely exceeds the precision allowed for a double. Why isn't an error thrown and how are the two things compared.

I would greatly appreciate any guidance on this. Thank you.

Jon Skeet
people
quotationmark

The first two are handled by the same case - JLS section 5.2:

In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

The third is simply a case of regular conversion from a literal in source code to a double: the nearest exact double to 6.0000000000000000000000000000000001 is 6.0. So if you had:

double d = 6.0000000000000000000000000000000001;

that would assign a value of 6.0 to d, as that's the closest representable double to the value specified in the source code.

people

See more on this question at Stackoverflow