This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

SCJP help

 
Maggie Ling
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rahuldf sharmadf
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also instance intialization is called after super class construction

for ex

class a
{
int a;

{
a=10;
}
a()
{
super()
// Now instance intializations will be called in top - down orders

}

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

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic