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

Static block and static variable

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can anybody clearly explain me that what is executed first? A Static block, a static method or static variables? What is sequence of execution of these following lines?

public class Static
{
static
{
int x = 5;
}

static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}

public static void myMethod()
{
y = x++ + ++x;
}
}

What will be the output? If you move the statis block below the static variable decalaration, why the output remains same.....

Please reply as soon as possible.

Dipti
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

As for i understood, the var i defined in the static block is no way affecting the output..because...its scope is confined to that block...
So the output will be 3

And if you define static block something like below.

static int x,y;
static
{
x = 5;
}
Output will be 23

Here order matters...if you interchange the stmts, you will get compilation error " illegal forward reference"...

So if static methods are initializing any of the static var then order matters..

That is what my understanding...
 
The government thinks you are too stupid to make your own lightbulb choices. But this tiny ad thinks you are smart:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic