Why is it that I don't see them quite frequently. I only see them mostly for networking, where size really does matter. But, for example, I have a variable that only uses numbers from the range 1-10, shouldn't I use byte? I am used to coding C/C++ using as small memory as possible, why isn't it like this in java?
-
I'm not 100% sure about this so I will post it as a comment. I wouldn't be surprised if it has something to do with Java needing to be managed by the Java runtime environment so what's the point of saving 16 bytes when it has to be stacked on top on an environment that is 1000x times its size anyways. C++ doesn't need this so saving those bytes may actually make a performance difference. – Loocid Mar 30 '15 at 04:09
-
Possible duplicate of http://stackoverflow.com/questions/402247/anyone-using-short-and-byte-primitive-types-in-real-apps – Raedwald Apr 04 '15 at 09:29
2 Answers
Actually in most processors that support Java, 32-bit integers are fastest to use. For example on Intel processors 32-bit integer registers have the shortest opcodes, while 16-bit integers are slightly slower to process. Furthermore most of the time using byte
s or short
s wouldn't save space for you.
It is not related to OOPness in any way; even in C that really does not have any kind of OOP concepts, it is very common to use int
for almost every number, because its size is often chosen so that it is the fastest width for the given architecture.

- 1
- 1

- 129,958
- 22
- 279
- 321
Unless it's something low level like bit masking or memory intensive where every byte each object takes up matters, I would probably use an int
even when a byte
might do.
Don't forget that Java objects are often padded to make accessing easier for the JVM. so depending on the other fields in your class, using a byte might still take up the same memory as an int! See javamex's explantation of Java's memory usage
If I know going in there are only really 10 possible values, from an OO way of thinking, I wouldn't consider using a byte
to store it. Why are the values only going to be from 1-10? Does each value mean something special?
If so, I would probably use an enum
and give each of those 10 values an intent revealing name.

- 31,188
- 3
- 63
- 67