• Post Reply Bookmark Topic Watch Topic
  • New Topic

final int conversion  RSS feed

 
Bindesh Vijayan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the following code:

And got an error.What confuses me although I
have used a simple variable to initialize the
final variable, and to me it appears that final
variables are initialized only once to change them into constants then why is the compiler so
indifferent to it when i assign a variable
instead of a int literal at 4.Then i changed the
code into this

And decompiled the class, guess what, i got byte variable being initialised at 4,instead of a constant, iam putting the decompiled version here:


Thanks
 
Charu Murali
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Here the value to i is assigned at runtime since it is an ordinary variable. So compiler doesn't know the value for the variable i which is assigned to a final variable. So you are getting an error.

HTH
Charu
 
Charu Murali
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I am sorry, I don't have any idea about your decompiled version.
Charu
 
Charu Murali
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shhh!! Is this post a reference to what Veena Point asked in another post titled " Conversions with final keyword please helpme understand "? I thought this is your doubt. So I answered. Anyway, I hope my answer is correct.
Charu
 
Bindesh Vijayan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah! It was my confusion, but sorry pal, still not clear
Thanks
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since the final variable k is initialized using another (not final, thus unknown at compile time) variable i, the assignment will happen at runtime. Had you instead initialized k using an int literal (literal are final, thus known at compile time), there wouldn't be any error bacause the compiler could deduce that the value contained in k fits within the bounds of the byte b1 and compilation would succeed.
 
Khurram Shahood(SCJP2)
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI
I THINK U R USING FINAL VARIABLE BEFORE USING.
AND U R ALSO CASTING A CONSTANT.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!