Forums Register Login

Using Final Keyword & Casting

+Pie Number of slices to send: Send
Compare following code

public class Cat{

public static void main(String args[]){

int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}


Compilation Error

java:8: possible loss of precision
found : int
required: byte
y = x;
^
1 error

Above code is OK, because I have to do casting like this

y =(byte) x;


but look at this


public class Cat{

public static void main(String args[]){

final int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}

This example prints 20 and no compilation error

I do not understand why it implicitly converts int to byte, when I use final keyword.

Thanks in advance.
+Pie Number of slices to send: Send
This is a situation of a narrowing primitive conversion.

Basically the reason that it works is that because the int value on the right of the assignment statement is a compile-time constant, and its value is compatible with a byte, the compiler will accept the assignment.
But how did the elephant get like that? What did you do? I think all we can do now is read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1129 times.
Similar Threads
Automatic typecasting
Fill the code
Final Byte variable
Static variables
accessing shadowed final values in method local inner class
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:19:24.