wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes SCJP help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "SCJP help" Watch "SCJP help" New topic

SCJP help

Maggie Ling

Joined: Sep 06, 2006
Posts: 8
Hi Guys, I have one small question with the following code:

1. class Banana {
2. int x = 1;
3. public static void main(String [] args) {
4. int x = 2;
5. Banana b = new Banana();
6. b.go();
7. }
8. { x += x; } // What is this?
9. void go() {
10. ++x;
11. System.out.println(x);
12. }
13. }

What is the result?
marc weber

Joined: Aug 31, 2004
Posts: 11343

Unmarked braces (line 8 in this code) denote "initializer blocks," which execute when the class is initialized. In this case, when an instance of Banana is created, the instance variable x (not the local variable x) is first initialized to 1, but then the initializer code increments it to 2.

Note: Braces preceded with "static" are "static blocks," which execute when the class is loaded.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Rahuldf sharmadf

Joined: Sep 18, 2006
Posts: 3
Also instance intialization is called after super class construction

for ex

class a
int a;

// Now instance intializations will be called in top - down orders


static public void main(strings args[])
new a();

I agree. Here's the link: http://aspose.com/file-tools
subject: SCJP help
Similar Threads
object ref assignment conversion
Please help with these questions
E practice exam questions for SCJP 5
Why Byte boxing doesn't work here
going bananas with this one