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

final  RSS feed

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyClass
{
public static void main(String []args)
{
final int i = 100;
byte b = i;
System.out.println(b);
}
}
when I compiled above code I got 100 as a output but if I removed final then i'm getting compilation error (about casting). I understand why I'm gettting compilation error cause integer value
is assigned to byte and you need casting. But why it's not giving this error when you use final?
Can somebody give me explantion?
Thanks,
Ash
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When given final ,it becomes a compile-time constant,Thus the 2nd statement considers the final var as a constant.
If you remove final ,it behaves as a normal variable whose value the compiler cannot determine during compilation ,hence the error
Rgs
Mousami
 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mausmi and Ash,


When given final ,it becomes a compile-time constant,Thus the 2nd statement considers the final var as a constant.
If you remove final ,it behaves as a normal variable whose value the compiler cannot determine during compilation ,hence the error


A slight correction here. You are right declaring a variable as
a final insures that the value "will" remain contant and its
content can't change. Infact, in such case the compiler can assume the value to be a literal. However, declaring a variable an int the compiler will know that the value in the "i" variable is subject to change so the optimization is not possible.
Take for instance,

Hope the point is clear now.
Ravindra Mohan.

 
Ash sav
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ravindra.
 
bacon. 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!