Author | Topic: Boone's mockexam question |
Thorpe unregistered |
posted February 29, 2000 05:55 AM
In Boone's mock exam he has given this qn.
} System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("4"); System.out.println("5"); His answer is c. " The method with all double parameters is actually the only version of test() that the Java Virtual Machine can legally coerce the numbers to. The reason the other versions of test() are not invoked is that at least one of the parameters would have to be automatically coerced from a type with greater accuracy to a type with less accuracy, which is illegal. "
|
Tony Alicea sheriff |
posted February 29, 2000 08:14 AM
It can't be (a) because the int 3 can't be converted to short automatically. The long 2L can be converted to double automatically, and so can the int 3.These "automatic" conversions are called widening conversions they are always OK and don't need a cast since no information is going to be lost by the conversion. The opposite, narrowing conversions, (as in (a), attempting to convert an
|
vasha unregistered |
posted March 08, 2000 02:01 PM
So why is this okay? byte b = 12; Isn't 12 an int? Why is it not necessary to do byte b = (byte) 12;
|
maha anna bartender |
posted March 08, 2000 03:15 PM
This is a special case called narrowing primitive conversion The rules for this are 1. The expression is a constant expression of type int. 2. The type of the variable is byte, short, or char. 3. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable. Here
|
vasha unregistered |
posted March 09, 2000 01:10 PM
Makes sense, but back to the original question. Why isn't ans. a correct? It seems to follow all 3 rules. By the way I did try it and ans. a was not correct, but I don't see why not.
|
maha anna bartender |
posted March 09, 2000 01:27 PM
Your qstn shows that you correctly UNDERSTOOD the concept. The above rule which I mentioned (automatic narrowing conversion) is applicable ONLY for assignment statements . For method invocation contexts it DOES NOT APPLY.. I am sorry that I should have mentioned this point in the previous post. So here the 3rd arg 3 is an int literal HAS TO BE casted to short in order to invoke this version of this method. I think I spoke to the point only. Any how I am happy that it MADE you to think..
regds maha anna
|
| | |