Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Initializer Code

 
sing
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which one statement is true about the application below?
1.class StaticStuff
2.{
3. static int x = 10;
4. static { x += 5; }
5. public static void main(String args[])
6.{
7. System.out.println("x = " + x);
8. }
9. static { x /= 5; }
10. }
Answer:
The code compiles, and execution produces the output x = 3.
My Question is how x = 3?
Thank You.
 
Tom Stevns
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code in like static{} will be executed one time before the rest therefore
x is 10, the 15 and at last 3
regards Tom
Originally posted by SteffySY Sing:

My Question is how x = 3?

3. static int x = 10;
4. static { x += 5; }
9. static { x /= 5; }


 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
freely quoting Mughal, A programmes guide to Java Certification, p 260f.
Java allows static initializer blocks to be defined in a class. Although such blocks can include abrbitrary code, they are primarily used for initializing static variables.
(personally me (Axel, not Khalid Mughal) do not use them).
The code in a static initializer block is executed just once when the class is initialized. Note that the static initializer blocks are n o t contained in any method. A class can have more than one static initializer block. The static initializer expressions (line 3) and the static initializer blocks (line 4, line 9) are executed in the order they are specified in the class.
A static block cannot make a forward reference to static variables that are defined after its definition (if you exchange the line 4 and 3 you get a illegal forward reference error at compile time, because variable x is not yet declared).
A typicall use of static initializer in a class is to load any external libraries that the class needs, for example, to execute native methods.
Originally posted by SteffySY Sing:
Which one statement is true about the application below?
1.class StaticStuff
2.{
3. static int x = 10;
4. static { x += 5; }
5. public static void main(String args[])
6.{
7. System.out.println("x = " + x);
8. }
9. static { x /= 5; }
10. }
Answer:
The code compiles, and execution produces the output x = 3.
My Question is how x = 3?
Thank You.


 
sing
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Tom and Axel.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic