I teach Java, I read Shildt. Already many times read that Java - strongly typed language. Why does the following code throw an error
int i = 10; i = i / 2.5; Does this code work fine and assign a value of 4 to i ?
int i = 10; i /= 2.5; I teach Java, I read Shildt. Already many times read that Java - strongly typed language. Why does the following code throw an error
int i = 10; i = i / 2.5; Does this code work fine and assign a value of 4 to i ?
int i = 10; i /= 2.5; This is how an assignment statement works, if a variable is of type int , and i / 2.5 type double , then you cannot assign a value of type double to type int without an explicit cast.
That is, type checking is performed before assigning a variable to a value. In the second case, the statement is an expression in which the value is converted to the type of the operand , that is, so that the operation can be carried out and back to the type of the variable where the value should be stored. I.e
int i = 10; d = i /= 2.5; will also work, since int values are converted to double before assignment without loss of accuracy, the reverse is not true and causes an error.
type operation
i /= 2.5; this is an automatic type casting operation that will be written as
i = (int) i/2.5; same with
double d = 1d; int i = 1; i = i * d; // ошибка i *= d; // нет ошибки with increment and decrement operations the same situation.
Source: https://ru.stackoverflow.com/questions/882065/
All Articles