I know this is a n00b question but I want to define a variable with a value between 0 and 100 in JAVA. I can use INT or BYTE as data types – but which one would be the best to use. And why?(benefits?)
I know this is a n00b question but I want to define a variable
Share
Either
intorbytewould work for storing a number in that range.Which is best depends on what you are aiming to do.
If you need to store lots of these numbers in an array, then a
byte[]will take less space than anint[]with the same length.(Surprisingly) a
bytevariable takes the same amount of space as aint… due to the way that the JVM does the stack frame / object frame layout.If you are doing lots of arithmetic, etc using these values, then
intis more convenient thanbyte. In Java, arithmetic and bitwise operations automatically promote the operands toint, so when you need to assign back to abyteyou need to use a(byte)type-cast.