WhatIf
WhatIf

Reputation: 653

How is a java byte stored?

A while ago I read that java byte which is an 8 bits is stored internally as an int. I don't seem to find any info online that affirms this.

Thank you for taking the time to answer my question!

What about C++ char? Is it stored as an 8 bits or 32 bits?

Upvotes: 0

Views: 653

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

How a byte (or any other Java value, for that matter) is stored is not specified by the JLS or the JVMS (the closest you'll find is the abstract specification on the level of the JVM, but that still doesn't say how it's stored natively). It is usually stored in the way which is most appropriate to the hardware architecture at hand, and that is usually 32 bits (or even 64).

Upvotes: 4

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44067

Well, if you look at how methods are represented in a class file, you will notice that method parameters are loaded onto a method frame's execution stack with the same byte code instruction if they are bytes, ints, booleans, shorts or chars. This implies that they need to take the same size within a method frame what usually takes 32 bit.

As of storing bytes on the heap, most JVM implementations choose to store bytes with 32 bit while byte arrays are stored with 8 bit per array entry. This is however not specified in the JLS or the JVMS. If you wanted to implement your own JVM, you could use any amount of bit to store a byte and still pass the Java TCK compatibility tests.

So to say: What you say is not a manifestured truth but it is still correct most of the time.

Upvotes: 1

Related Questions