Why does int = int * double give an error, but int * = double does not (in Java)?

Why does the assignment of the form int = int * double give an error, and the 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 accepted, but r = r * e is not. Why?

+5
source share
2 answers

r = r * e gives you an error, because the result of r * e is double , so when you save it to int will lose precision.

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

+9
source

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

 r = (int) (r * e); 
0
source

Source: https://habr.com/ru/post/1244978/


All Articles