This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static and final

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,got it from http://www.go4java.20m.com/mock1.htm

public class finex
{
final static int fi=0;
final int fn;
static
{
fi=6;
}
{
fn=8;
}

}

why can't we assign value for final static variable fi in initializer block and also in constructor?
but this is possible with static variable fi.

Please explain me....

Thanks
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why can't we assign value for final static variable fi in initializer block and also in constructor?
but this is possible with static variable fi.


You cannot assign value to a final static constant inside instance initializer block or constructor as you can use static fields even without making an instance of the class. So the final constant must be initialized with declaration or in a static initializer block.

eg



This is why final constants must be assigned a value in their declaration or static initializer blocks as they run when the class is loaded...
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankit,
but i can initialize final variable in initializer block and not in constructor.how about this?
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can initialize final non-static constants in initializers as well as constructors but not both...
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Preetha Arun:
Hi Ankit,
but i can initialize final variable in initializer block and not in constructor.how about this?


you cant assign the final variable in init block. because it will be called everytime new object is created.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

you cant assign the final variable in init block. because it will be called everytime new object is created.


You CAN assign a final variable in an initialization block because each new object you create will have it's own instance of the variable, unless it's static.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic