• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static variable vs Static initializer

 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I have simple question.I know the static initializer block will run first when the class is loaded.But when the value of static field is assigned after the initializer block
for eg.

class{
static {
stint = 100;
stint1=1000;
}
private static int stint = 10;
private static int stint1;

public static void main(String[] args) {
System.out.println(stint);
System.out.println(stint1);
}
}

If i run this class why it is showing the outputp as 10 and 1000 instead of 100 and 1000.

If the order is matter i.e (first initializer block then static variables) then it should display 0 for stint1 right?

But if i place both the private statements before the static block then i m getting output as 100 and 1000?
Please Explain.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Order does matter for the assignments. The static initialization goes like this:

1) Static variables are declared
2) Static variable assignments and static blocks are executed in the order they are declared.

So in your example:


Acts like:

 
You are HERE! The other map is obviously wrong. Better confirm with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic