Question

For a simple addition as follows -

public class TestAddition {

    public static void main(String args[]){
        Double a = 1.4278175434624698E9;
        Double b = 0.0;
        int c = 0;
        c += a;
        c += b;
        System.out.println("Sum is " + c);
    }

}

I am getting output as Sum is 1427817543

If i am using Integer , instead of int , its neatly throwing an error ,but for this , its not giving an error and is producing this output. Is this a java bug ?

Was it helpful?

Solution 2

Are you confused about the unboxing conversion?

From type Integer to type int

From type Double to type double

If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()

If r is a reference of type Double, then unboxing conversion converts r into r.doubleValue()

And compound assignment operators?

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So this

c += a;

becomes

c = (int) (c + a);

in which case we have addition and the operands are promoted.

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

If either operand is of type double, the other is converted to double.

So a becomes

a.doubleValue();

The whole expression becomes

c = (int) ((double) c + a.doubleValue()

Now, this wouldn't work if c was an Integer because the expression would be

c = (Integer) (c + b);

in which case c + b is addition and the same promotion rules as before apply.

c = (Integer) ((double) c.intValue() + a.doubleValue());

but the double value result of the addition cannot be cast to an Integer, so it fails. Basically, don't use the compound assignment operator with wrapper (boxed) types.

OTHER TIPS

This is not an error. You are assigning value to int so anything after the decimal point is ignored.

1.4278175434624698E9

is the same as:

1427817543.4624698

so becomes:

1427817543

when you assign it to int

The value is correct since an int cannot contain decimals.

When you do c+= b, b is first converted to integer, since int and double are convertible types. Integer and double are not convertible, and you get an error.

Note that you should always use BigDecimal for calculating decimal values in Java, else you might get some strange results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top