My code looks like this
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] argv)
{
Scanner keyboard = new Scanner(System.in);
byte q1 = keyboard.nextByte() * 10;
}
}
It gives me an error Type mismatch: cannot convert from int to byte.
Why would Java store a literal operand that is small enough to fit in a byte, into an int type? Do literals get stored in variables/registers before the ALU performs arithmetic operations?
The problem is the line byte q1 = keyboard.nextByte() * 10;
. There are no arithmetic operations on byte
or short
. The value of keyboard.nextByte()
is casted up to an int
prior to multiplication with 10, which is also an int
. The result of the multiplication is an int
, which can not be stored into q1
if it’s defined as a byte
.
Possible solutions would be to cast the result of the multiplication to a byte using (byte) (keyboard.nextByte() * 10)
or by changing the type of q1
to int
.
Unfortunately, I’m not finding a reference to this in the tutorials. However, you can find an explanation in the Java Language Specification. Sections 5.6.2 Binary Numeric Promotion and 15.18.2 Additive Operators (+ and -) for Numeric Types define this behavior.
4