Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

javacaps mock 2 Q:25

 
Haining Mu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Answer: C
I did see anything wrong with multiplication, the error is Initialization of variable "Integer", it need cast. so answer is D, right?
 
william shen
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The right answer should be C.Here need int cast to byte,then
byte Integer =byte(Byte * Double);should be ok.
Originally posted by Haining Mu:
[B]
Answer: C
I did see anything wrong with multiplication, the error is Initialization of variable "Integer", it need cast. so answer is D, right?[/B]


------------------
 
Amit Madan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ans c is correct because
the value of Byte & Double is not final it may be changed so it is not definat that
multiplication of them will be in the range of byte(-128 to 127).so it give compile time error
if we made both of them final then it will run properly.
Amit Madan
 
Geoff Tate
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit,
I think the correct answer is that the all math operands are promoted to at least an int before being used in an operation. The operands are both promoted to ints causing the result to be an int which clearly will not fit in a byte. casting it should work. I don't see what final has to do with it.
 
Muhammad Farooq
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit is very much right, if the variable(of integral data type) are declared as final and their operartion(i.e /, * , +, - etc) remain within their limits, casting is not required.
 
Amit Madan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
binary numeric promotion implicitly appropriate widening primitive conversion so that a pair of operands have the broadest numeric type of two,but which is always at least int.
byte,short,char always converted to at least int.
here both of them are variable so they can be changed.so multiplication of them can be an integer which may be not in rang of byte so compiler give error with msg ossible loss of precision.so explisit casting requird where definatly loss of precision.
if you make them final then value of them are constant so it can't be changed and here multiplication is within the range of byte so then it work properly because no precision loss.
Amit Madan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic