Hello Everyone, while going thru the mock exam at Jtips.net I came across this question. <pre> Given: class Q14 { public static void main(String[] args) { int intNumber = 123456789; float floatNumber = intNumber; int x = (int)floatNumber; System.out.println(intNumber - x); System.out.println(intNumber == x ); } } Choose 2 answers. 1.Prints 0 and true . 2.Prints 0 and false. 3.Prints (some number due to loss of precision) and true. 4.Prints some integer due to loss of precision and false. </pre> Can anyone please tell me can we expect this kind of questions in the certification exam as I think this kind of questions should not come into exam which asks you questions like at what range the int -> float conversion will loose some precision? Any comments?
I guess this very question is perfect for the exam because it test your knowlegde of numeric values. I think any SJCP should know the result of the program. I wouldn't find reasonable they will ask the exact diference though.
How can I tell which number will cause loss of precision in this case? If I replace 123456789 with: 5 -> no loss 500,000,000 -> no loss 500,000,001 -> loss 500,000,002 -> loss 500,000,010 -> loss 500,000,020 -> no loss I cannot see a general rule of thumb. Please shed some lights. The code that I use to test this: public class Test { public static void main(String[] args) { int intNumber = (new Integer(args[0])).intValue(); float floatNumber = intNumber; System.out.println("min: " + Math.min( Integer.MAX_VALUE, intNumber)); System.out.println(floatNumber); int x = (int)floatNumber; System.out.println("x is " + x + " so " + (intNumber - x)); System.out.println(intNumber == x ); } }