I am trying to understand the following code:
public class A {
private void doTask() {
doInt(99);
}
public short doInt(short s) {
return 100;
}
}
The code gives a compiler error on line "doInt(99)".
The method doInt(short) in the type A is not applicable for the arguments (int)
Can someone explain why it's giving me the error.
In java, the default type of an integer number is an int
. Java will automatically upcast (eg from short
to int
), but will issue a warning with downcasting (eg from int
to short
) because of possible loss of data.
The fix for your code is this:
doInt((short)99);
This explicit downcast changes the 99
(which is an int
) to a short
, so there's no (further) possible loss of data.
Try
public class A {
private void doTask() {
doInt((short)99);
}
public short doInt(short s) {
return (short)100;
}
}
Java thinks that all literals (such as 99 or 100) in your program is int.
If you pass big number, 12345678 for example, it will be cutted to fit to short
value. Java cannot cut number without you, so you must do it yourself. That way you see that you casting int to short
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