Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Type casting of final variable  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The above code runs fine and prints 100.

But when I am removing 'final' keyword from the int variable i , I am getting compiler error:-



Can anyone please explain the cause?
This is from a question I have come across in a Certification website.

Thanks
 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's probably because the compiler knows that if final 'i' with value 100 can not change and therefore will definetely fit into a byte, but if it wasn't final it could be assigned another much larger value that wouldn't.

Not 100% but that's what it would lead me to think.
 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When variable i is declared as final, compiler knows what value it shall have at runtime, and in this case it is 100 which is in range of byte primitive -128 to 127. So no compile time error.

However if you remove word final, some other value might have been assigned to variable i before value of i is assigned byte b, so explicit time cast is required this time. Same thing, if you change value of i to be more than 127 even if it is final.
 
Well behaved women rarely make history - Eleanor Roosevelt. tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!