• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

There are some things that only the Creator(s) can explain !

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello All,
Try out this program :
==================================================
public class TestStatic {

static
{
System.out.println("This is strange !!!");
}
public static void main(String args[]) {
TestStatic ts = new TestStatic();
}

}
==================================================

What would we expect ?
A compilation error ?
But this prints :
+--------------------------------+
| |
| This is strange !!! |
| |
+--------------------------------+
on the screen .
Any explanations ?
We are preparing for the JDK-1.4 Exam.
Cheers,
gurucharan
 
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When a class is accessed for the first time, the static block is executed. That is why you are getting that output.
[ February 19, 2003: Message edited by: Barkat Mardhani ]
 
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gurucharan Murudeshwar:
Hello All,
Try out this program :
==================================================
public class TestStatic {

static
{
System.out.println("This is strange !!!");
}
public static void main(String args[]) {
TestStatic ts = new TestStatic();
}

}
==================================================

What would we expect ?
A compilation error ?
But this prints :
+--------------------------------+
| |
| This is strange !!! |
| |
+--------------------------------+
on the screen .
Any explanations ?
We are preparing for the JDK-1.4 Exam.
Cheers,
gurucharan


There is nothing strange about it.
static {} is called a static initializer
A static initializer block executes only once and this happens even before an instance of the class is created.
i,e even before
TestStatic ts = new TestStatic();
Hope this helps,
Sri
---------------
when in doubt, refer to Java Language Specification
[ February 19, 2003: Message edited by: Sri Sri ]
 
Gurucharan Murudeshwar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes.
But is this a normal behaviour ?
Cheers.
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gurucharan Murudeshwar:
Yes.
But is this a normal behaviour ?
Cheers.


Yes that is the normal behaviour.
some more to start with

https://coderanch.com/t/192804/java-programmer-SCJP/certification/Static-Initializers[/URL]
https://coderanch.com/t/194459/java-programmer-SCJP/certification/Static-Non-Static-Blocks
Sri
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Posted by Sri:

There is nothing strange about it.
static {} is called a static initializer
A static initializer block executes only once and this happens even before an instance of the class is created.
i,e even before
TestStatic ts = new TestStatic();
Hope this helps,
Sri


I agree with Sri. But I would add that static initializer is executed when the class is ACCESSED (i.e. an object is created or a static value is accessed). Otherewise static initializer is not executed.
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wouldnt it really depend on the particular JDK policy of loading classes?
From what I understand though, a static initializer block is guaranteed to execute "Before" any access to the class happens. Which means, it could at the latest happen just before the first access of any kind to the class happens.
Though if you had a specific import, like
import com.blah.blah.blahclass;
,wouldnt this specific import cause the static initializers to be loaded?
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
These are the three phases a class undergoes before it can be used:
a) Load. The exact time a class is loaded into the JVM depends on the implementation of it. An early strategy could load the classes as they appear in the source code and those classes that are referred to by them. Also it is possible to load the classes in related groups. A common strategy is load the classes due to the first appearance of the name of the class in the text.
b) Linking.
b1) Verification of the bytecodes, compliance with the format of the class file and much more.
b2) Preparation. The static variables are assigned space in the static data area. They are initialized to its default values (0, null)
b3) Resolution. The symbolic references in the constant pool are replaced by direct ones. It is optional until the first use of the reference.
c) Intialization. The static variables receive the values specified by the programmer. That is, the static initializers and static variable intitializers are executed (in order of appearance).
The exact time the intialization happens is not a subject for the exam. However...
A class is initialized because of the first active use of it.
Active uses of a class are:
The creation of an instance of it.
An access to one of its static members.
The initialization of a subclass.
[ February 19, 2003: Message edited by: Jose Botella ]
 
Gurucharan Murudeshwar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello All,
Generally, we use the static methods by saying
someObj.thatStaticMethod();
But here, the instantiation itself triggers the println line.
Can someone explain the need o such a functionality ?
Cheers,
gurucharan
 
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe if you wanted to initialize a collection.

This would allow for some preliminary initialization from a properties file.
 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gurucharan Murudeshwar:
Hello All,
Generally, we use the static methods by saying
someObj.thatStaticMethod();
But here, the instantiation itself triggers the println line.


When you type "java TestStatic" on the command line, the JVM will load the TestStatic class and will execute the static main method: TestStatic.main(args). It is this that causes the static initializer to be executed, not the instantiation of an instance of TestStatic. This can be verified by adding some printlns to the code:

The output is:
This is strange !!!
Before instantiation
After instantiation
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good point John
Onther active use of a class is its designation as the "principal" for an aplication, that is holding the main method.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Generally, we use the static methods by saying
someObj.thatStaticMethod();
But here, the instantiation itself triggers the println line.
Can someone explain the need o such a functionality?


Do not confuse the static methods with the static initializers of the form
static {....}
or with the static variable initializers like this
static field int = 4;
The compiler gathers the code of all the static initializers and all the static variable intializers in textual order and places them in the class initialization method (*) . This method is executed, upon the first active use of the class, to provide for the initialization of the static fields that are not constants with a known value at compile time. Fields that are constant with a value known at compile time see their occurances in the text program replaced with the proper value itself by the compiler. After all they are not going to change. Are they?
Anyway coming back to the question. A static initializer is necessary instead of a static variable initializer in the cases the initialization code does not fit in a single sentence. For instance, if some exception handling is needed put the try/catch clauses within a static initializer.
(*) use javap -c MyClass to check this
 
reply
    Bookmark Topic Watch Topic
  • New Topic