wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static method 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 "Static method" Watch "Static method" New topic
Author

Static method

Todd Bahrs
Greenhorn

Joined: Feb 17, 2004
Posts: 7
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

Joined: Feb 18, 2004
Posts: 96
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.


Rich
SCJP 1.4
Todd Bahrs
Greenhorn

Joined: Feb 17, 2004
Posts: 7
Thanks Richard, I found a good explanation of static intializers on developer.com.
Todd
sameer kumar
Greenhorn

Joined: Mar 22, 2004
Posts: 13
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static method
 
Similar Threads
static var. and static blcok, which is initialized first?
forward referencing
How is a compile-time constant static vaiable causing initialization???
Initialization/assignment of instance variables outside constructor/methods.
Explain the output