Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jvm expands byte & short to int before pushing on stack?

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)
like image 668
Prateek Avatar asked Aug 27 '13 15:08

Prateek


People also ask

What is native method stack in Java?

Native Method Stacks. An implementation of the Java Virtual Machine may use conventional stacks, colloquially called "C stacks," to support native methods (methods written in a language other than the Java programming language).

What does JVM store in the stack?

A JVM stack stores frames, also called “stack frames”. A JVM stack is analogous to the stack of a conventional language such as C — it holds local variables and partial results, and plays a part in method invocation and return.”

How does Java byte code look like?

class files consist of a bunch of bytecodes. Bytecode is to Java what assembler is to C++. Each bytecode is a number no larger than a byte and has a mnemonic. The numbers and their mnemonic are what you have listed in your question.


1 Answers

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.

like image 146
Lars Brinkhoff Avatar answered Nov 14 '22 22:11

Lars Brinkhoff