Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Dan's Mock (Dec. 4)

 
Emiko Hori
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've been working on Dan's Mock Exam Questions (excellent site, BTW) and came up with a quesiton.
On Comprehensive Exam 3 No. 3, the question was:
Which of the following statements will generate a compile-time error?
a. Short s1 = new Short(1);
b. Short s1 = new Short('1');
c. Short s1 = new Short(1L);
d. Short s1 = new Short('b' - 'a');
e. Short s1 = new Short(1.0);
f. Short s1 = new Short((short)1 - (short)2);
g. Short s1 = new Short((byte)1);
h. Short s1 = new Short((short)1);
i. None of the above.
Dan's answer was b, c, d, e, f. When I compiled it, answer "a" also got a compiler error because we are passing an int. According to Dan's explanation:
"The Short wrapper class has two constuctors. One accepts an argument of type short and the other accepts a String. There is no implicit widening conversion from the primitive types char, int, long, float or int to type short so those types can not be passed as an argument to the constructor without an explicit cast to the primitive short type. Please note that if both operands of a binary arithmetic expression are of type byte, char or short then both are implicitly widened to type int and the result of the expression is of type int."
In that case, answer "a" has to be a compiler error as well, right? Please correct me if I'm wrong. I'm new to Java! Thanks so much for help.
 
Keen Chen
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think u are right.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Emiko,
You are correct. Thank you for using my exams and for pointing out that error. I'll upload the correction in a few minutes.
 
John Paverd
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was a very interesting question (John-speak for 'I would have got that one wrong')
Java will do an implicit narrowing conversion on assignment, but, to quote the JLS:
Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion (�5.2).

That means that some of the constant expressions in the constructor arguments could be assigned to a primitive short variable, even though they cannot be used as argument values for the Short constructor:
 
Emiko Hori
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan, thanks for the reply as well as your exams!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic