Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help me:what 's the difference among these 3 mothods?

 
Mike Lin
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte m1() {
final short s=2 ;
return s; // 1
}
byte m2() {
final short s ;
return s;
}
byte m3(final short s) {
return s;
}
comile m2()or m3() will complain of:
" possible loss of precision"
but m1() is ok.
why???
I really get sick !
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short S in m1() is what we call a "Compile Time Constant", its value is known at compile time and is unchangiable during run time since the variable is declared final.
2 is in the range of byte, so there will NOT be any loss of precesion at run time, the compiler knows that.
In m1(), m2() although the variables are declared final, they are not assigned a value yet, so maybe they will have the value 140 which when converted to byte from short will be chopped and loses preceision, so the compiler warns.
HTH
 
Mike Lin
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks!:-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic