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?
Data types are divided into two groups: Primitive data types - includes byte , short , int , long , float , double , boolean and char. Non-primitive data types - such as String , Arrays and Classes (you will learn more about these in a later chapter)
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte , the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
byte is a primitive data type similar to int, except it only takes up 8 bits of memory. This is why we call it a byte. Because the memory size is so small, byte can only hold the values from -128 (-27) to 127 (27 – 1).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With