my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Basic question on final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Basic question on final" Watch "Basic question on final" New topic

Basic question on final

Mintoo kumar
Ranch Hand

Joined: Aug 21, 2007
Posts: 61

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.

Adinath Shirsath
Ranch Hand

Joined: Dec 04, 2007
Posts: 35
it seems like compiler recgonizes that value of s1 is not going to change and it fit's in byte
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265


This is a frequent question on the JavaRanch. Check out Jesper's answer in this recent topic.

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

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.

Thanks & Regards
Sidharth Pallai
Mintoo kumar
Ranch Hand

Joined: Aug 21, 2007
Posts: 61
Thanks to all.

I got it.
It is sorta covered in the JavaRanch Style Guide.
subject: Basic question on final
Similar Threads
doubt in primitive assignment...
implicit casting of final int to byte ???
Q how does the above code give error and the code below doesn't???
final modifier and primitive conversion
narrowing convertion in case of final