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

Basic question on final

 
Mintoo kumar
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks,

i have following lines of code.
_________________________________
short s = 1;
byte b = s; // compiler to error .
_________________________________

It's ok.i understand.but what if i write the above line in way like

_____________________________________________________

final short s1 = 1;
byte b = s; // no error . it works
_____________________________________________________

It means we can't assign final to non-final ?
Does anybody have any idea what's the reason.

Thanks,
Amit
 
Adinath Shirsath
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it seems like compiler recgonizes that value of s1 is not going to change and it fit's in byte
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit,

This is a frequent question on the JavaRanch. Check out Jesper's answer in this recent topic.
 
Sidharth Pallai
Ranch Hand
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mr. Adinath is absolutely right.Recognising final varaible compiler treat it as compile-time constant.Provided the constant is in range of byte.Try assigning a value 128 to final short variable and the re-assign to byte.You will get to know the consequences.
 
Mintoo kumar
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all.

I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic