Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 11 down vote accepted

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.

share|improve this answer
1  
+1: Good answer and direct references to the JLS are always win. –  Deco Oct 11 '12 at 0:10
    
For anyone interested: number literals are integers in .NET too. –  Simon Whitehead Oct 11 '12 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? –  Chris Okyen Oct 11 '12 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 '12 at 19:18
    
@ThomasOwens Thanks. –  Chris Okyen Oct 12 '12 at 1:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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