When to use primitive numbers range
Hi
I am a noob and was just wondering in what programming situations I would use javas various number primitives e.g. int, double, byte, long, short, float.
The only situations I have used numbers is:
int - to represent whole numbers
double - to represent decimals, real life example would be prices
Can anyone give me real life examples of where I might use the other number primitives?
Many thanks
[443 byte] By [
javakida] at [2007-10-2 16:58:44]

long -- to represent integers whose value is outside the range of int
byte -- to represent single bytes, usually for I/O or low level "binary" manipulation.
short, float -- I don't think I've ever used them. I guess you'd use them if you wanted an integer or floating point number that doesn't take up as much space as int or double, and you're willing to live with the loss of precision and range. But with memory being as cheap as it is, and the limited range and precision of short and float, the situations where this makes sense are probably quite rare.
jverda at 2007-7-13 18:11:51 >

> Can anyone give me real life examples of where I
> might use the other number primitives?
Actually to use double (or floating points in general) for currency isn't such a good idea because of rounding problems. An integral type like int or long is a much better alternative for handling "prices".
Floats are often used in graphics applications because it's the "natural" floating point type in OpenGL.
Say you need to store a huge number of integers in an array. You can cut the memory requirements in half by using shorts instead of ints.
So I'd say all primitives have their uses but int and double are probably the most frequently used. If you standardize on them you also avoid implicit conversions in expressions which makes life a lot easier.
jverda at 2007-7-13 18:11:51 >

> Sorry if i'm missing something, but would you
> represent prices e.g. ?.50 using int or long?
I usually use long but it depends on the likely figures involved. int would do you unless the national debt or something is involved.
Pence/cents is the natural way to represent money.
It's anoying, actually, that there's no provision for this in the NumberFormat classes.