• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

Static method

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Richard, I found a good explanation of static intializers on developer.com.
Todd
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Time flies like an arrow. Fruit flies like a banana. Steve flies like a tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic