• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

static block

Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

Why following code do not give muktiple declaration error for variable x and what will be the flow of this program. Please explain.
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Amir

static block in a class will be executed first when the class is loaded

so when normally people use static block to initialize some their variables

so for you to understand better try this program!!!

class teststatic
{int x=10;
static int x;
// Initialize a value and check what happens
static int y;

public static void main(String[] args)
{ System.out.println(x); //#5
System.out.println(y); //#6
//teststatic t1= new teststatic(); //#7
} }

So in static block if u declare an int x and intialiaze it to 10 nothing wrong is there
but the only thing is that the scope of the varial int x will be only inside the static block!!!

but if u have declared static int y and initialize this y inside the static block , it's scope is through out that class

and for your question there will not be any multiple declaration erros as int x is only inside static block and static int x will be through out the class

hope this might help you
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you will get answer of 0,0 because
the variable declared in static block will become local to that block,it will not conflict with field x,so the static field is still not initialized so it will have a value of 0 and field y will also have a value 0 (they will automatically initialize to default values as they are fields) and you initialized local variable x to 10 which will die after static block,

i hope you understood.
Ranch Hand
Posts: 2023
incandescent light gives off an efficient form of heat. You must be THIS smart to ride this ride. Tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic