In my casting class, teacher taught us an interesting fact as follows.
class Casting {
public static void main(String args[]){
int i = 10;
byte b = i;
System.out.println(b);
}
}
We got an error
java:5: possible loss of precision
And then we changed the code as follows
class Casting1 {
public static void main(String args[]){
final int i = 10;
byte b = i;
System.out.println(10);
}
}
10
We got the correct output. As for the reason, he told that when we modify a variable final
the variable is stored in the smallest data type possible. In this case was a byte
. That's the reason that we were able to cast that without using the cast keyword.
But when we use method overloading like this,
class A {
void m(int i){
System.out.println("int");
}
void m(byte b){
System.out.println("byte");
}
public static void main(String args[]){
A a1 = new A();
final int i = 10;
a1.m(i);
}
}
I get the output int
. If the final variables are stored in the lowest possible data type, it should be byte
. So I tried the following code without overloading.
class A {
void m(byte b){
System.out.println("byte");
}
public static void main(String args[]){
A a1 = new A();
final int i = 10;
a1.m(i);
}
}
java:9: m(byte) in A cannot be applied to (int)
What's the reason for this? Is there any point that I have misunderstood?
You are mixing up memory space of variables and their type. Calling the method m(...) will first of all check the type of the paramether variable. Here it is an int so it will chose the according overloaded method, no matter the size of the int in memory.
Although I really apreciate you first example that brings the light into one of the characteristics of the final identifier.
This bit isn't quite correct...
"As for the reason, he told that when we modify a variable final the variable is stored in the smallest data type possible. In this case was a byte."
It doesn;t store it as a byte, it stores it as an int, BUT it is effectively a constant so when Java compiles the line byte b = i;
it knows for sure that the value will be 10, which doesn't need casting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With