Tuesday, May 22, 2018

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




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?


Answer




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).


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...