Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about static clause

 
Steven Gao Song
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}

I cannot understand why "int x = 5;" is not executed.
Thank you.
 
Saira Dhanani
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cannot understand why "int x = 5;" is not executed.


The Static block is executed i.e. int x = 5 is executed
but int x declared in the static block is local to the block
hence it has no effect on / is not related to the static variable x.

 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static block is executed and a local int variable is set to 5.
 
Steven Gao Song
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it. Thanks a lot.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic