Evaluate the following Java expression, where a, b and c are integers and d and f are floating-point numbers. The values are a = 5, b = 3 and d = 1.5. c = a – (b++)*(–d)
Advertisements
Question
Evaluate the following Java expression, where a, b and c are integers and d and f are floating-point numbers. The values are a = 5, b = 3 and d = 1.5.
c = a – (b++)*(–d)
Advertisements
Solution
a = 5, b = 3, d = 1.5
Data types: a, b, c are integers, while d and f are floating-point numbers.
Expression: c = a - (b++) * (-d)
In Java, the post-increment operator (b++) uses the original value of b first and then increases its value by 1.
Original value of b = 3
Value used by b++ = 3
Updated value of b = 4
The unary minus operator (-d) changes the sign of d from 1.5 to -1.5.
c = a − (b++) × (−d)
c = 5 − 3 × (−1.5)
c = 5 − (−4.5)
c = 5 + 4.5
c = 9.5
Since d is a floating-point variable, the expression produces a floating-point result of 9.5.
As c is an integer variable, Java does not allow a double value to be assigned directly to an int variable without explicit type casting.
