Reputation: 319
I have been writing a program in java. If I assign an integer to a byte variable, it compiles correctly as follows:
byte test = 1;
But if I pass the same integer to a method argument that takes a byte I get error incompatible types: possible lossy conversion from int to byte
double result = myClass.subtractNumbers(1,2,3);
public double subtractNumbers(byte a1, int a2, int a3)
My question is why the compiler does not show error in the first case but show errors in the second case ? Following is the complete code :
public class MyClass {
public static void main(String args[]) {
MyClass myClass = new MyClass();
byte test = 1; // this line does not show any errors
double result = myClass.subtractNumbers(1,2,3); // But this call shows error
System.out.println("function result : " + result);
}
public double subtractNumbers(byte a1, int a2, int a3){
double sum = a1 + a2 + a3;
return sum;
}
}
Upvotes: 0
Views: 761
Reputation: 2541
When you assign a numeric literal, the value of that literal is known at compile time. If that value is in the byte range, compiler allows that assignment. Similarly, this statement will give compilation error.
byte test = 1000;
incompatible types: possible lossy conversion from int to byte
For the 2nd case, as per the method signature the method takes argument of type. Now method doesn't know with what values will it be called. So when you call the method passing an integer value, it cannot keep the guarantee that value will lie in the byte range. So compiler just outright throws an error.
Lets say compiler did allow that method call, then this would have happened
int a1 = 5; int a2 = 8; int a3 = 10;
subtractNumbers(a1, a2, a3); // this would have been OK
a1 = 1000;
subtractNumbers(a1, a2, a3); // this would not have been OK
Because of this ambiguity, compiler throws error.
Upvotes: 0