MJ Riddles
MJ Riddles

Reputation: 11

Java primitive types promotion confusion

I am new to this as you may be able to tell, please clarify to a beginner how the following code snipped outputs -2.50 as the answer. I'm still very confused around the promotion/demotion subject in terms of int -> double.

    int x = 5;
    double y = 2.5;
    double q = x / 10 - y;
    System.out.printf("%.2f\n",q);

The way I see it is: double q = 5.0 (x promoted to double from int) / 10.0 - 2.5 Which would be equal to 0.5 - 2.5 = -2.00 (2 decimal places because of "%.2f\n")

Why is the correct answer -2.50 and not -2.00?

Upvotes: 1

Views: 183

Answers (4)

Manisha
Manisha

Reputation: 136

double q = x / 10 - y; In this since division has greater precedence than subtraction therefore x/10 will execute first and here we are dividing two ints ( irrespective of the fact that the variable where final answer is stored is a double), so answer will be an integer i.e 5/10 = 0 and then subtraction of an int and double will be done (here int will be promoted to a double). So effectively it is 0.0 - 2.5 now, thus answer is -2.50

Upvotes: 1

QBrute
QBrute

Reputation: 4536

You could also write your expression like this:

double q = (x / 10) - y;

Now inside the parenthesis there are no doubles, so it's a pure int-division, which gives 5 / 10 = 0. After that you have

double q = 0 - y;

Now you have a difference of an int with a double. And here is where the promotion from (int)0 to (double)0.0 takes place.

The final result will be

double q = 0.0 - 2.5; //q == -2.5

Upvotes: 2

chengpohi
chengpohi

Reputation: 14217

double q = x / 10f - y;

x / 10 // it will be thought as int

Upvotes: 0

Yogesh Patil
Yogesh Patil

Reputation: 888

X is an integer and the value of x/10 would yield 0 and not 0.5( because x and 10 are both int). If you do x/10.0, then the output would be 0.5.

Upvotes: 4

Related Questions