Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is addition of byte converts to int because of java language rules or because of jvm?

Tags:

byte a = 1;
byte b = 1;
byte c = a + b;

Throws error: possible loss of precision

byte subt = a_s - a_b;
                ^
  required: byte
  found:    int

Is this behavior has something to do with jvm or its been defined in java language .

EDIT : And if it is defined in java language then does it because of keeping jvm in mind ?

Means if java supports byte datatype then why operation on byte results int

like image 381
Prateek Avatar asked Aug 28 '13 08:08

Prateek


Video Answer


2 Answers

if java supports byte datatype then why operation on byte results int

Because that's how the Java Virtual Machine is designed. There is no instruction set to perform operation on a byte type. Rather the instruction set for int type is used for the operation on boolean, byte, char, and short types.

From JVM Spec - Section 2.11.1:

A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.

The reason behind this is also specified in that section:

Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a byte. [...] Separate instructions can be used to convert between unsupported and supported data types as necessary.

For the details on what all instruction sets are available for various types, you can go through the table in that section.

There is also a table specifying the mapping of actual type to the JVM computational type:

like image 60
Rohit Jain Avatar answered Oct 12 '22 22:10

Rohit Jain


JLS 5.6.2: Binary Numeric Promotion covers it:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

like image 35
Bernhard Barker Avatar answered Oct 13 '22 00:10

Bernhard Barker