3

I know that if we are performing arithmetic operations on byte value,then implicitly it is promoted to an int and the result will be an int,and hence we need to explicitly convert it into byte in order to store the result in a byte variable. But I wanted to ask-

  • Does the conversion from byte to an int happens at the time when it is declared or does it happens when we use it in arithmetic operation? Because the java decompiler I am using converts it from byte to an int at the time of declaration.So,is it the decompiler problem or is it really so.
  • And if it really happens at the time of declaration,then why storing a value beyond the range of byte shows an error?

Eg- The code is-

public class Hello
{
    public static void main(String[] args)
    {
        byte a=90;

    }
}

Output from decompiler- Check this

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

3 Answers3

5

A byte remains a byte, and is as such statically typed by the compiler.

The JVM machine implements holding a single byte (as opposed to a byte array) as variable in an int slot. And uses int opcodes for arithmetic.

Also assigning a final int constant to a byte will be done by the compiler, as long as it is in the byte range -128, ... 127.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
3

Implicit type conversion in Java is a compile-time mechanism. So yes, it will show errors such as value beyond range. Here is a great SO answer on this topic:

Runtime vs Compile time

Community
  • 1
  • 1
Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
  • 1
    The linked topic does not mention type conversion, and I do not think that you did this question justice, so I downvoted. How do you know that implicit type conversion happens at compile time? – Rainbolt Aug 26 '15 at 14:06
0

The compiler will crop any value declared on the stack to an integer, if it is within range.

Taken from infoq article

When loading a value onto the operand stack, the JVM treats primitive types that are smaller than an integer as if they were integers. Consequently, it makes little difference to a program’s bytecode representation if a method variable is represented by, for example, a short instead of an int. Instead, the Java compiler inserts additional bytecode instructions that crop a value to the allowed range of a short when assigning values. Using shorts over integers in a method’s body can therefore rather result in additional bytecode instructions rather than presumably optimizing a program.

James Wierzba
  • 16,176
  • 14
  • 79
  • 120