Size of a byte in memory - Java

I have heard mixed opinions over the amount of memory that a byte takes up in a java program.

I am aware you can store no more than +127 in a java byte, and the documentation says that a byte is only 8 bits but here I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency.

Can anyone clear this up, and would this be an implementation specific issue?

Asked by: Byron878 | Posted: 28-01-2022

Answer 1

Okay, there's been a lot of discussion and not a lot of code :)

Here's a quick benchmark. It's got the normal caveats when it comes to this kind of thing - testing memory has oddities due to JITting etc, but with suitably large numbers it's useful anyway. It has two types, each with 80 members - LotsOfBytes has 80 bytes, LotsOfInts has 80 ints. We build lots of them, make sure they're not GC'd, and check memory usage:

class LotsOfBytes
    byte a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
    byte b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
    byte c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
    byte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
    byte e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;

class LotsOfInts
    int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
    int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
    int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
    int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
    int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;

public class Test
    private static final int SIZE = 1000000;

    public static void main(String[] args) throws Exception
        LotsOfBytes[] first = new LotsOfBytes[SIZE];
        LotsOfInts[] second = new LotsOfInts[SIZE];

        long startMem = getMemory();

        for (int i=0; i < SIZE; i++)
            first[i] = new LotsOfBytes();

        long endMem = getMemory();

        System.out.println ("Size for LotsOfBytes: " + (endMem-startMem));
        System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));

        startMem = getMemory();
        for (int i=0; i < SIZE; i++)
            second[i] = new LotsOfInts();
        endMem = getMemory();

        System.out.println ("Size for LotsOfInts: " + (endMem-startMem));
        System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));

        // Make sure nothing gets collected
        long total = 0;
        for (int i=0; i < SIZE; i++)
            total += first[i].a0 + second[i].a0;

    private static long getMemory()
        Runtime runtime = Runtime.getRuntime();
        return runtime.totalMemory() - runtime.freeMemory();

Output on my box:

Size for LotsOfBytes: 88811688
Average size: 88.811688
Size for LotsOfInts: 327076360
Average size: 327.07636

So obviously there's some overhead - 8 bytes by the looks of it, although somehow only 7 for LotsOfInts (? like I said, there are oddities here) - but the point is that the byte fields appear to be packed in for LotsOfBytes such that it takes (after overhead removal) only a quarter as much memory as LotsOfInts.

Answered by: Sam220 | Posted: 01-03-2022

Answer 2

Yes, a byte variable in Java is in fact 4 bytes in memory. However this doesn't hold true for arrays. The storage of a byte array of 20 bytes is in fact only 20 bytes in memory.

That is because the Java Bytecode Language only knows two integer number types: ints and longs. So it must handle all numbers internally as either type and these types are 4 and 8 bytes in memory.

However, Java knows arrays with every integer number format. So the storage of short arrays is in fact two bytes per entry and one byte per entry for byte arrays.

The reason why I keep saying "the storage of" is that an array is also an object in Java and every object requires multiple bytes of storage on its own, regardless of the storage that instance variables or the array storage in case of arrays require.

Answered by: Carlos254 | Posted: 01-03-2022

Answer 3

Java is never implementation or platform specific (at least as far as primitive type sizes are concerned). They primitive types are always guaranteed to stay the same no matter what platform you're on. This differs from (and was considered an improvement on) C and C++, where some of the primitive types were platform specific.

Since it's faster for the underlying operating system to address four (or eight, in a 64-bit system) bytes at a time, the JVM may allocate more bytes to store a primitive byte, but you can still only store values from -128 to 127 in it.

Answered by: Byron159 | Posted: 01-03-2022

Answer 4

A revealing exercise is to run javap on some code that does simple things with bytes and ints. You'll see bytecodes that expect int parameters operating on bytes, and bytecodes being inserted to co-erce from one to another.

Note though that arrays of bytes are not stored as arrays of 4-byte values, so a 1024-length byte array will use 1k of memory (Ignoring any overheads).

Answered by: Arthur156 | Posted: 01-03-2022

Answer 5

I did a test using Note that I am using 64-bit Oracle/Sun Java 6, without any compression of references etc.

Each object occupies some space, plus JVM needs to know address of that object, and "address" itself is 8 bytes.

With primitives, looks like primitives are casted to 64-bit for better performance (of course!):

byte: 16 bytes,
 int: 16 bytes,
long: 24 bytes.

With Arrays:

byte[1]: 24 bytes
 int[1]: 24 bytes
long[1]: 24 bytes

byte[2]: 24 bytes
 int[2]: 24 bytes
long[2]: 32 bytes

byte[4]: 24 bytes
 int[4]: 32 bytes
long[4]: 48 bytes

byte[8]: 24 bytes => 8 bytes, "start" address, "end" address => 8 + 8 + 8 bytes
 int[8]: 48 bytes => 8 integers (4 bytes each), "start" address, "end" address => 8*4 + 8 + 8 bytes
long[8]: 80 bytes => 8 longs (8 bytes each), "start" address, "end" address => 8x8 + 8 + 8 bytes

And now guess what...

    byte[8]: 24 bytes
 byte[1][8]: 48 bytes
   byte[64]: 80 bytes
 byte[8][8]: 240 bytes

P.S. Oracle Java 6, latest and greatest, 64-bit, 1.6.0_37, MacOS X

Answered by: Adelaide725 | Posted: 01-03-2022

Answer 6

It depends on how the JVM applies padding etc. An array of bytes will (in any sane system) be packed into 1-byte-per-element, but a class with four byte fields could either be tightly packed or padded onto word boundaries - it's implementation dependent.

Answered by: Steven895 | Posted: 01-03-2022

Answer 7

What you've been told is exactly right. The Java byte code specification only has 4-byte types and 8-byte types.

byte, char, int, short, boolean, float are all stored in 4 bytes each.

double and long are stored in 8 bytes.

However byte code is only half the story. There's also the JVM, which is implementation-specific. There's enough info in Java byte code to determine that a variable was declared as a byte. A JVM implementor may decide to use only a byte, although I think that is highly unlikely.

Answered by: John338 | Posted: 01-03-2022

Answer 8

You could always use longs and pack the data in yourself to increase efficiency. Then you can always gaurentee you'll be using all 4 bytes.

Answered by: Charlie254 | Posted: 01-03-2022

Answer 9

byte = 8bit = one byte defined by the Java Spec.

how much memory an byte array needs is not defined by the Spec, nor is defined how much a complex objects needs.

For the Sun JVM I documented the rules:

Answered by: Lydia178 | Posted: 01-03-2022

Answer 10

See my MonitoringTools at my site (

class X {
   byte b1, b2, b3...;

long memoryUsed = MemoryMeasurer.measure(new X());

(It can be used for more complex objects/object graphs too)

In Sun's 1.6 JDK, it seems that a byte indeed takes a single byte (in older versions, int ~ byte in terms of memory). But note that even in older versions, byte[] were also packed to one byte per entry.

Anyway, the point is that there is no need for complex tests like Jon Skeet's above, that only give estimations. We can directly measure the size of an object!

Answered by: Patrick585 | Posted: 01-03-2022

Answer 11

Reading through the above comments, it seems that my conclusion will come as a surprise to many (it is also a surprise to me), so it worths repeating:

  • The old size(int) == size(byte) for variables holds no more, at least in Sun's Java 6.

Instead, size(byte) == 1 byte (!!)

Answered by: Lucas956 | Posted: 01-03-2022

Answer 12

Just wanted to point out that the statement

you can store no more than +127 in a java byte

is not truly correct.

You can always store 256 different values in a byte, therefore you can easily have your 0..255 range as if it were an "unsigned" byte.

It all depends on how you handle those 8 bits.


byte B=(byte)200;//B contains 200
System.out.println((B+256)%256);//Prints 200
System.out.println(B&0xFF);//Prints 200

Answered by: Grace149 | Posted: 01-03-2022

Answer 13

It appears that the answer is likely to depend on your JVM version and probably also the CPU architecture you're running on. The Intel line of CPUs do byte manipulation efficiently (due to its 8-bit CPU history). Some RISC chips require word (4 byte) alignment for many operations. And memory allocation can be different for variables on the stack, fields in a class, and in an array.

Answered by: Ryan880 | Posted: 01-03-2022

Similar questions

scala vs java, performance and memory?

performance - How to debug Java memory errors?

There is a Java Struts application running on Tomcat, that have some memory errors. Sometimes it becomes slowly and hoard all of the memory of Tomcat, until it crashes. I know how to find and repair "normal code errors", using tests, debugging, etc, but I don't know how to deal with memory errors (How can I reproduce? How can I test? What are the places of code where is more common create a memory error? ).

performance - Load text file to memory in Java

I have wiki.txt file and its size is 50 MB. I need to do several things on the file and so I thought that the best way in terms of performance is to load the file to memory, is that correct? This is the code that I written: File file = new File("wiki.txt"); FileInputStream fileInputStream = new FileInputStream(file); FileChannel fileChannel = fileInputStream.getChannel(); Ma...

performance - Used and free Memory in Java

I am trying to improve the performance of my web-application so I decided to do profiling of it. When doing this I noticed that after completion of a long process when I start task manager I saw that java.exe is taking too much memory. By the way I've checked it after 2-3 hours after the process complete and cpu is in stable state. I saw in the profiler's VM elementry view, Use...

Java VM memory performance - Are Array writes faster than Array reads?

I performed a short benchmark on a long array in java with quite strange results. It seems that sequential reads with random writes are faster - half the time - than random reads with sequential writes. Has anyone a clue why?? Here are two methods that write an array of some longs (run with -Xmx2G or so) by random when reading sequentially and read sequentially when writing by random: import java.ut...

java - Memory vs Performance, which would be best?

I need to take an image, scale it, mask it, add a background in case some of it is transparent and then add an overlay image. To do this I've written the following: Canvas canvas = new Canvas(); Bitmap mainImage = Bitmap.createScaledBitmap(((BitmapDrawable)d).getBitmap(), iconSize, iconSize, false); Bitmap result = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); canvas.setBitmap(result);...

how to get performance of CPU and Memory using Netapp API and Java?

I want to get performance of storage system using Netapp API and Java. I am able to fetch volumes, Aggregates, Disks info. Now I want to get memory and CPU utilization of a system. Which class should I use in order to get information related to CPU and memory? I use apirunner object to call various classes in API. Here is a code for a connection.. Protocol protocol = Protocol.INS...

Java .vs. C# Memory Usage and Performance

Closed. This question needs to be more focused. It ...

java - Performance vs memory Lists

What would be better ? Say we would have a certain class mainClass which has a List&lt;BigClass&gt; with List&lt;Foo&gt;foos.... Foo itself has a List&lt;Boo&gt; If the goal was to be able to get all the Boo's for all the elements of foos. Would it then be better to keep another List&lt;Boo&gt; wi...

performance - Java: get data fast: store in memory vs read from file

Iam writing a data table generator tool and have some performance problems - I need to care about RAM usage and time of generating. That is really a key in my program. 1) I need to store final data in a single file (one file = one table, to load it later when all files will be generated), like: 111|aaaa|bbba 112|aaab|bbbb 113|aaac|bbbc 114|aaad|bbbd...

Performance question: Fastest way to convert hexadecimal char to its number value in Java?

I want to convert from char representing a hexadecimal value (in upper or lower case) to byte, like '0'-&gt;0, '1' -&gt; 1, 'A' -&gt; 10, 'a' -&gt; 10, 'f' -&gt; 15 etc... I will be calling this method extremely often, so performance is important. Is there a faster way than to use a pre-initialized HashMap&lt;Character,Byte&gt; to get the value from? Answer

performance - Java very large heap sizes

Closed. This question needs to be more focused. It ...

java - Is there a performance difference between Javac debug on and off?

If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal.

java - How to improve Netbeans performance?

Is there a real way to get Netbeans to load and work faster? It is too slow and gets worse when you have been coding for some time. It eats all my RAM. I am on a Windows machine, specifically Windows Server 2008 Datacenter Edition x64, 4Gb of RAM, 3Ghz Core 2 Duo processor, etc. I am using the x64 JDK. I use the NOD32 Antivirus since for me it is the best in machine performance. In Task Manage...

java - Is there a performance difference between a for loop and a for-each loop?

What, if any, is the performance difference between the following two loops? for (Object o: objectArrayList) { o.DoSomething(); } and for (int i=0; i&lt;objectArrayList.size(); i++) { objectArrayList.get(i).DoSomething(); }

performance - Java File Cursor

Is there some library for using some sort of cursor over a file? I have to read big files, but can't afford to read them all at once into memory. I'm aware of java.nio, but I want to use a higher level API. A little backgrond: I have a tool written in GWT that analyzes submitted xml documents and then pretty prints the xml, among other things. Currently I'm writing the pretty printed xml to a temp file (my lib woul...

performance - Accelerate 2D images in Java *without* disturbing JMenus

Already implemented performance boosters : - Get compatible image of GraphicsConfiguration to draw on - Enable OpenGL pipeline in 1.5: Not possible due to severe artifacts So far I am fine, the main profiled bottleneck of the program is drawing an image with several thousand tiles. Unfortunately it is not regular, else I simply could set pixels and scale them. I accerelated the image with VolatileImages and own ren...

performance - Measuring Java execution time, memory usage and CPU load for a code segment

For a particular segment of Java code, I'd like to measure: Execution time (most likely thread execution time) Memory usage CPU load (specifically attributable to the code segment) I'm a relative Java novice and am not familiar with how this might be achieved. I've been referred to

Can anyone quantify performance differences between C++ and Java?

Java was initially slow before the JIT but today performance is pretty close to C++. I want to know if someone has done measurable performance comparisons between the two languages? Where does Java fall short when compared to C++? Java provides many productivity gains to developers so they can write applications much quicker because of garbage college, lack of pointers, etc. Applications such as Firefox, Webkit ...

performance - ArrayList vs. Vectors in Java if thread safety isn't a concern

Is there really that much of a difference between the performance of Vector and ArrayList? Is it good practice to use ArrayLists at all times when thread safety isn't an issue?

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)