Asked 11 years, 7 months ago
Active 1 year, 2 months ago
Viewed 66k times
51
8
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).
Follow
15.4k1414 gold badges8282 silver badges130130 bronze badges
asked Apr 27 '10 at 13:05
10.3k1010 gold badges5858 silver badges5959 bronze badges
1
Are 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.– Tedil
Apr 27 '10 at 14:201
@Tedil Yes an assignment of this kind is possible since Java 1.5, thanks to a feature know as "autoboxing". The primitive number2
is an int
, which is boxed to an Integer
, which is a subclass of Number
.
Apr 27 '10 at 14:2326
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.