• Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding Final

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Himai Minh
Ranch Hand
Posts: 1400
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!