A byte as a local variable is implemented as an int
, so it takes 4 bytes.
A byte as a field of a class (like in your example) takes 1 byte of memory, but classes in memory are rounded up to multiples of 8 bytes on e.g. HotSpot JVMs. That said, if you have a class with multiple byte
fields (or char
or short
fields), those will make more efficient use of memory.
Arrays are similar: each byte
will take 1 byte, but the array as a whole will be rounded up to a multiple of 8 bytes on e.g. HotSpot JVMs.
You can experiment with this by hand using http://openjdk.java.net/projects/code-tools/jol/. If you use it, for example, on
public static class A {
boolean f;
byte g;
int h;
}
I get
Running 64-bit HotSpot VM.
Using compressed oop with 3-bit shift.
Using compressed klass with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
org.openjdk.jol.samples.JOLSample_01_Basic.A object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header) N/A
12 4 int A.h N/A
16 1 boolean A.f N/A
17 1 byte A.g N/A
18 6 (loss due to the next object alignment)
Instance size: 24 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 6 bytes external = 6 bytes total
which exhibits pretty clearly that boolean
and byte
take one byte as object fields.
As you'd expect, char
and short
are 2 bytes, int
and float
are 4 bytes, long
and double
are 8 bytes.
https://stackoverflow.com/a/14782255/869736 explains some details on Dalvik, including that currently small fields like byte
are in fact implemented with 4 bytes. Remember that these details are going to be VM-dependent.