Please read this code: 1. class Example extends Object{ 2. public void Increment( Short S ){ 3. S = new Short( S.intValue() + 1 ) ; 4. } 5. public void Result( int x ) { 6. Short X = new Short((short) x ) ; 7. Increment( X ) ; 8. System.out.println( "New value is " 9. + X ) ; 10. } 11. } What happens when a program calls the Result method with a value of 30? A. The message "New value is 31" goes to the standard output. B. The message "New value is 30" goes to the standard output. C. A runtime exception is caused due to the cast in line 6. D. The message "New value is null" goes to the standard output.
why the answer is B? THANK YOU. [ July 12, 2005: Message edited by: Barry Gaunt ]
SCWCD 1.4(Loading...), SCJP 1.4(98%), Bachelor of Engineering (computer science)
You should get a compile time error as there is no Constructor with int argument in a Short Class. [ July 12, 2005: Message edited by: Srinivasa Raghavan ]
Srinivasa is correct: This won't compile without a cast in line 3.
Assuming the constructor call was fixed, then the answer would be B, because arguments are copies of references (that is, passed by value) and their variables are local to the method.
In line 6, a Short object is created and assigned to variable X. In line 7, the increment method is called and a copy of X's reference is passed. In the increment method, that reference copy is assigned to variable S, which is local to the method. So, when S is reassigned (to a new Short wrapping a different value), this does not effect the original object that X is still referencing.
(Note that these wrapper instances are immutable anyway.) [ July 12, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org