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

Dan's Q doubt again?

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Again,

Answer is
22 d Compile-time error at 2. There is a compile-time error at 2. The short type variable, s, is not a compile-time constant, so it can not be assigned to type byte without an explicit cast. The statement, "return s;", is a return statement with an expression, s. A compile-time error occurs if the type of the expression is not assignable to the declared result type of the method. The declared result type of the method, m4, is byte. The return statement attempts to return the value of the short type variable, s. If a short value is a compile-time constant, and if the value falls within the range of type byte, then the short value is assignable to type byte. In method m4, variable s is not a compile-time constant, so the value of variable s is not assignable to type byte. While the declaration of method m4 produces a compile-time error, the declaration of method m2 does not; because the variable is a compile-time constant with a value, 2, that is assignable to type byte.
I can understand the explanation given above as "If a short value is a compile-time constant, and if the value falls within the range of type byte, then the short value is assignable to type byte."
But as explained " In method m4, variable s is not a compile-time constant", now is the variable s in m4 not compile time constant as it is passed as method argument (although it is a final variable ??)

Plz. clarify,I thought it to be constant
Thanks,
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We cannot return a type that is larger in range to the smaller type... Even though it is final, the word "final" has nothing to do with the type range...
But if u cast the return type into byte like the following, u can compile the program....

Hope u got it...
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

...now is the variable s in m4 not compile time constant as it is passed as method argument (although it is a final variable ??)

Yes, the value of the variable is not known until run-time; therefore, it can not be a compile-time constant.
 
Dan Gun
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So it is almost in the same line as :
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic