aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Bit confusing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Bit confusing" Watch "Bit confusing" New topic
Author

Bit confusing

Ramkumar Venkat
Greenhorn

Joined: Dec 09, 2002
Posts: 7
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

Joined: Sep 23, 2002
Posts: 109
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 !!


--Shweta<br />SCJP 1.4 <br />SCWCD
Ramkumar Venkat
Greenhorn

Joined: Dec 09, 2002
Posts: 7
It did, Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Bit confusing