• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Daught

 
Rafael Andrade
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello there. I was looking around this site, and saw the following code from a previous thread:

class A{
static{
int x = 5;
}
static int x,y;
public static void main(String args){
doStuff();
System.out.println(y++ + x + ++x);
}
static void doStuff(){
x++;
++y;
}
}

But I didn�t understand this part:

static{
int x = 5;
}

what�s that? It isn�t a constructor, and not a method, and no inner class. So what can it be?

Thanks.
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rafeal,

They are initializer blocks. This one above is a static initializer block.

Regards,
Jothi Shankar Kumar. S
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initialization
 
Rafael Andrade
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry,
sorry about that, I knew that you had a policy,but I changed the name and didn�t remember that. I will change right away.

Owen,
thanks for the link. I don�t remember reading about this on the SCJP book,
but I think it must be there somewhere.

cya!
 
Matthew Gerald
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, keep in mind...

static{
int x = 5;
}

is not the variable that will be used in main or doStuff(), the x variable that is used will be initialized to 0 (thus resulting in an answer of 4).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic