3

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?

1 Answer 1

12

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
  • 1
    +1: Good answer and direct references to the JLS are always win.
    – Deco
    Oct 11, 2012 at 0:10
  • For anyone interested: number literals are integers in .NET too. Oct 11, 2012 at 0:27
  • @Thomas Owens What do you mean "There are no arithmetic operations on byte or short? Do you mean there isn't any in my expression, or Java doesn't allow it, and must cast it up as an int, which allows arithmetic operations? Is this why keyboard.nextByte() casts up to int? Oct 11, 2012 at 19:06
  • 1
    @ChrisOkyen The operations +, -, /, *, and I believe % are not defined for type byte or short. Variables of type byte or short are casted to int if they are used with one of these operations. It's all explained in the links I provided to the Java Language Specification.
    – Thomas Owens
    Oct 11, 2012 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.