File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Daught Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Daught" Watch "Daught" New topic
Author

Daught

Rafael Andrade
Greenhorn

Joined: Aug 04, 2006
Posts: 15
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

Joined: Sep 26, 2006
Posts: 9243
    
    1

Hi Rafeal,

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

Regards,
Jothi Shankar Kumar. S


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Initialization
Rafael Andrade
Greenhorn

Joined: Aug 04, 2006
Posts: 15
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

Joined: Sep 11, 2006
Posts: 10
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).


-------------------------<br />SCJP 1.4 10/28/2006<br />SCWCD (next on the list!)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Daught
 
Similar Threads
Differance in int[](array) and int...(var args)
Wrappers
code explanation needed
Boxing/Unboxing
SCJP Chapter 01 Self Test Qn no. 3