• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bit confusing

 
Ramkumar Venkat
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I execute the code below I get the output
j : 7.2000003
i : 8.0
float i = 8; // 1
float j = i/10 * 9; //2
System.out.println("\n j : " + j + "\n i : " + i); //3
But if I replace i in line 2 with 8,
ie., float j = 8/10 * 9;
the output is
j : 0.0
Can anyone explain why if the variable is replaced by a constant the operator precedence is discounted.
 
shweta mathur
Ranch Hand
Posts: 109
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramkumar,
this is not because of a constant value, but because u have replaces a float with an int.
Try
float j = 8.0f/10 * 9; //2 at line 2 and you will get the correct answer.
The reason is in first case i is float and so all the operands are converted to float(8.0f/10.0f = 0.8f) and then the expression is solved.
In second case when you replace i by 8 (as constant which is an integer) , all the operands remain int, ( 8/10 = 0) and then the answer is upcasted to float.
Hope this helps !!
 
Ramkumar Venkat
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It did, Thanks
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic