byte = 8-bit integer, signed, range = [-2^7, 2^7 - 1] short = 16-bit integer, signed, range = [-2^15, 2^15 - 1] int = 32-bit integer, signed, range = [-2^31, 2^31 - 1] long = 64-bit ingeger, signed, range = [-2^63, 2^63 - 1]
I feel better typing all that info
My question is: Why should we bother using byte, short and int, when we could get away with long? Obviously a long number type uses up more memory, but does it make a difference when you look at the big scheme of things? [ March 11, 2007: Message edited by: D.W. Smith ]
Good question. I guess it just comes down to using the right tool for the right job. Granted, memory is cheap, and we don't have to be as frugal with it as in the old days. However there's still no need to squander it recklessly. In communications applications, you're not just talking about memory, you're talking about bits being sent across a wire, and there frugality is still very much in order.
In my own applications, I find that the choice is most often between int and long. I very rarely bother with byte or short unless I'm coding a communications application. Byte and Byte are used a lot in dealing with streams of data.
From a practical standpoint, an int still allows for a number up to around 2 billion, so for most anything I need a temporary variable to do (loop counters, array indexes, etc.) that's plenty. Why use up more memory and processing time if I don't have to? I use long mostly for things like keys in database applications where I want to make doubly sure that I'll never run out of keys. It's still a good idea to keep this question in the back of your mind every time you declare a variable of type int or Integer: Could this number ever be over 2 billion? [ March 11, 2007: Message edited by: Merrill Higginson ]
There are several issues I can think of, but is not likely an exclusive list.
1. Not all methods/constructor take a long, but byte, int, etc. So what happens if you only use long, and need to pass it as a smaller variable and the value of the long exceeds the smaller data type max or min value? Integer overflow is tough to deal with in Java.
2. Yes, it is a waste of space, and the attitude that "memory is cheap so who cares" is poor, IMO.
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle