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 Initializer Expression

 
Pasupathi J
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I would like to know the exact order of construction of an object. I believe that it should be
1. Static Initializer expressions
2. Static Initializer blocks( order in which they are defined)
3. Constructor header ( super or this � implicit or explicit )
4. Instance variables initialization / Instance initializer block(s)execution
5. rest of the code in the constructor
I need explaination for the following behaviour.
Example 1.
class test1
{
static int i = init();
static int init(){ return j;}
static int j = 1;
public static void main(String args[])
{
System.out.println(i);
}
}
Here the output is 0. This is fine as per Maha anna's discussion. Because the variable is accessed before it is initialized. Consider the same code with slight modification below.
Example 2
class test1
{
static int i = init();
static int init(){ return j;}
static final int j = 1;
public static void main(String args[])
{
System.out.println(i);
}
}
Now the output is 1. How this is happening.

Regards,
pasupathi J
 
nitin sharma
Ranch Hand
Posts: 290
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think because static final member varaible's are not initialized by the compiler.U get the final value which in any case would be the assigned value,final varaible's are constant,therefore value's to final varaible's can only be assigned just one not twice,Now think if compiler initialise the final variable with the value 0 then it would not have benn able to assign the value 1 to the final varaible,because value's to the final are provided just once not again and again.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pasupathi J,
Would you please read the JavaRanch Name Policy
and re-register using a name that complies with the rules.
Thanks for your cooperation.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic