• 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

Doubt regarding a static block

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a doubt regarding a static block. Here i have two classes(C1,C2).

_______________________________________________
class C1
{

static int x=10;

static
{
intx=99;
}

public static void main(String args[])
{
System.out.println("The value of x is : "+x);
}
}
_________________________________________________

class C2
{

static int x=10;

static
{
x=99;
}

public static void main(String args[])
{
System.out.println("The value of x is : "+x);
}
}

____________________________________________________

C1 produces an output of 10.
Whereas C2 produces 99.

What is exactly happening inside the static block??

-phil
 
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the first case..the local scoped 'x' will not be available in main..

so here the class level accessible x with a value 10 is available
and printed out

In the second case

the class level varaible is modified ...in the block...


In both the cases...this block that is the static block is executed at class loading...(they are not executed at instance creation)


and the main method has access to the static class level variable x ..

not the static block level ..x

Hope u got it...

Regards
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Phil, the x in c1 is local to the static block and has no scope outside of the block. If you replace the int x = 99 with x = 99 the static value will be set to 99.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic