File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Bit confusing" Watch "Bit confusing" New topic

Bit confusing

Ramkumar Venkat

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
this is not because of a constant value, but because u have replaces a float with an int.
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

Joined: Dec 09, 2002
Posts: 7
It did, Thanks
I agree. Here's the link:
subject: Bit confusing
It's not a secret anymore!