• 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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

final variable

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class General
{
final int i ;
General()
{
seti();
System.out.println("Value of i= "+i);
}
public void seti()
{
i=10;
}
public static void main(String args[])
{
General g=new General();
}
}

This gives complie time error as cannot assign a value to final variable i
I am trying to intialise the final varible i just before it is printed in constructor.
If i initialise i=10 in the constructor itself everything works fine
Thanx
Nivedeeta
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification, Section 8.3.1.2, final Fields states the following.


A blank final instance variable must be definitely assigned (�16.8) at the end of every constructor (�8.8) of the class in which it is declared; otherwise a compile-time error occurs.

 
veda patil
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this mean that we have to intialise the blank final variable in the constructor?
Thanx,
Nivedeeta
 
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although the JLS does not mention the use of an instance initializer, the following code demonstrates that you could initialize a blank final variable there.

It appears that the compiler wants the blank final variable initialized before the instance construction process is complete. Although your code actually does that, the compiler apparently does not check to see if a method call might be doing the job for the constructor.
 
Gold Digger
Posts: 7610
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!