This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static method

 
Todd Bahrs
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Can someone explain why this static method is executed prior to the println
statements ? I don't understand how it gets called.
class Static {
static int b;
static int a = 3;
static void method(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static { // how does this get called first ?
System.out.println("static block initialized");
b = a * 4;
}
public static void main(String args[]) {
method(42); // Calls the method 'method' and passes 42 to 'int x'.
}
}
Prints out:
static block initialized
x = 42
a = 3
b = 12
Thanks
Todd
 
Richard Quist
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you have is not a static method...it doesn't have a method name, return type, etc...
It's a static initializer that gets executed when the class is loaded.
 
Todd Bahrs
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Richard, I found a good explanation of static intializers on developer.com.
Todd
 
sameer kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi todd
the sequence of initilization is given below remember it
when u creat object.
1. first static field(class varibles)
2. static initilizer block.
3. instance mamber
4. initilizer block
5. constructor.
normaly we read that constructor is the first stattement called.
but this is the actual happened behind this
i think it is clear now if u have any problem
call again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic