5

java code : ,

byte a_b = 12;
short c_d = 14

replaces in bytecodes with

bipush  12 // expands byte1 (a byte type) to an int and pushes it onto the stack
sipush   14 // expands byte1, byte2 (a short type) to an int and pushes it onto the stack

Why jvm does that expansion, and not use byte & short ?

Also when i open bytecode of my file

EDIT : short var = 14 is replaced by bipush 14 rather than sipush 14

Is my understanding is not clear or is there a bug ?

enter image description here

I am using following version

java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)
6
  • 1
    See stackoverflow.com/a/17094810/724361 . Commented Aug 27, 2013 at 15:20
  • 2
    Mainly because that's the way they defined it, and there's no compelling need to have it defined differently. (The stack is conceptually only incremented/decremented in 4-byte increments, though a little tap-dance obviously must occur in 8-byte JVMs.) Commented Aug 27, 2013 at 15:38
  • And a bipush is 2 bytes long, while a sipush is 3 bytes long. Why use the longer instruction when the shorter works just as well? Commented Aug 27, 2013 at 15:44
  • @HotLicks see the snap added from following link docs.oracle.com/javase/specs/jvms/se7/html/… Commented Aug 27, 2013 at 15:50
  • You mean "At any point in time, an operand stack has an associated depth, where a value of type long or double contributes two units to the depth and a value of any other type contributes one unit. "? Commented Aug 27, 2013 at 16:14

1 Answer 1

8

Because (conceptually) the smallest unit of data on the JVM stack is 32 bits. So there is no way to increase the size of the stack with just 8 bits.

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6.2

At any point in time, an operand stack has an associated depth, where a value of type long or double contributes two units to the depth and a value of any other type contributes one unit.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean decrease ;-) Also you could only write 8 bit of data into a 32 bit stackframe. I just would be a waste of space. I think the real reason is found in the answer @TheTerribleSwiftTomato has linked in the comments.
@stonedsquirrel - They do write the 8 bits of data into the 32-bit stack frame. And then they sign-extend into the rest of the frame.
@HotLicks Of course. That you not only could do it but have to with a fixed stack frame size skipped my mind ;-) Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.