Asked 11 years, 7 months ago
Active 1 year, 2 months ago
Viewed 66k times
I have two Numbers. Eg:
Number a = 2; Number b = 3; //Following is an error: Number c = a + b;
Why arithmetic operations are not supported on Numbers? Anyway how would I add these two numbers in java? (Of course I'm getting them from somewhere and I don't know if they are Integer or float etc).
15.4k1414 gold badges8282 silver badges130130 bronze badges
asked Apr 27 '10 at 13:05
10.3k1010 gold badges5858 silver badges5959 bronze badges
1Are they actually assigned like that? I mean, is Number a = primitiveNumber valid? If you are getting them from some Method which returns "something extends Number" you could actually check whether the returned Number is an instanceof Double or Float or BigDecimal or whatever.
– TedilApr 27 '10 at 14:20
1@Tedil Yes an assignment of this kind is possible since Java 1.5, thanks to a feature know as "autoboxing". The primitive number
int, which is boxed to an
Integer, which is a subclass of
Number. Apr 27 '10 at 14:23
You say you don't know if your numbers are integer or float... when you use the
Number class, the compiler also doesn't know if your numbers are integers, floats or some other thing. As a result, the basic math operators like + and - don't work; the computer wouldn't know how to handle the values.