aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Understanding Final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Understanding Final" Watch "Understanding Final" New topic
Author

Understanding Final

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 300



What I think is final instance variable get their default values if not initialized
class Finale
{ final int x;
final String s;
public static void main(String args[])
{
System.out.println(new Finale().x);
System.out.println(new Finale().s);
}
}

compiler says x might not have been initialized
So does that mean final instance variable don`t get their default values.

and the other one is

class Cant_Initialize
{
final int x;
public static void main(String args[])
{
Cant_Initialize c=new Cant_Initialize();
c.x=10;
}
}

Now compiler says can`t assign value to a final variable

so does it means that final instance variable have to be initialized when they are declared

class Constant
{
final int x=10;
}

Last one , final without static .So does it mean that every instance of class Constant will have its own final int x variable.
And since it makes no sense that each instance to have a final variable so we make it static


Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 801
    
    1
Hello Mahtab,
Answers to your 3 questions:
1. final variable means a contant variable. The compiler won't initialize it for you because it does not know what constant value you will assign to the final variable. If the compiler set x =0 at the beginning, what if you change x to 10 later?
For this reason, the compiler sets a rule that final variable should be initialized in the declaration or in the constructor.

2. In Cant_Initialize, final variable should be assigned a value in a contructor or declaration.This can prevent programmer to re-assign values to the constant variable.

3. Yes. Each instance has its own constant variable.
Douglas Mortimer
Greenhorn

Joined: Mar 30, 2000
Posts: 7
Just to add, the third place you may assign a value to a final variable is in an initialization block (static or instance). Both execute before the class's constructor completes, which is what is required.
 
Don't get me started about those stupid light bulbs.
 
subject: Understanding Final