Why does int = int * double give an error and int *= double does not (in Java)? [duplicate]
Asked Answered
L

2

5

Why does an assignment of the form int = int * double give an error, and an assignment of the form int *= double does not give an error (in Java)?

Example:

public class TestEmp {

    public static void main(String[] args) {

        double e = 10;
        int r = 1; 
        r *= e;

        r = r * e;
        System.out.println("De uitkomst van r :" + r);

    }
}

r *= e is accepted and r = r * e isn't. Why?

Langue answered 13/3, 2016 at 22:22 Comment(0)
M
11

r = r * e gives you an error because the result of r * e is a double so there will be a loss of precision when you store it in an int.

r *= e does not give you an error because it is syntactic sugar for r = (int)(r * e) (source).

Misericord answered 13/3, 2016 at 22:27 Comment(0)
G
0

It is because r and e are different types. When using compound assignment operators such as *=, the types are narrowly converted behind the scenes (implicitly). The * operator does not implicitly convert, thus you must explicitly convert by casting inward:

r = (int) (r * e);
Gender answered 13/3, 2016 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.