174k views
5 votes
If the result of an arithmetic expression is assigned to a variable with a type that could cause a loss of data when the conversion is performed, you should

User Kavin Smk
by
3.8k points

1 Answer

2 votes

Answer:

use type casting.

Step-by-step explanation:

int total = (int) (7.7 + 5.2);

The above code snippet is in Java. The sum of 7.7 and 5.2 is assigned to an integer variable called total. Normally, the result is 12.9, a double, but if you use type casting this way, the result will be 12, an integer. This way, you tell the Java "I know what I am doing. Even though these two double numbers produce a double result, I will cast it to the int so that I will have the integer part of the result".

Note that if you do not use type casting in this example, Java will give you an error, saying something like "possible lossy conversion".

User Patrick Lightbody
by
4.3k points