• 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

static

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}}
When will the string "Hi there" be printed?
A - Never.
B - Each time a new instance is created.
C - Once when the class is first loaded into the Java virtual machine.
D - Only when the static method is called explicitly.
The answer is C, but what meaning have line 2? I have never seen static word alone.
thanks in advance.
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

The second line in your program is static initializer code.
Static initializer code gets executed during class load time
So The answer for your question is 'c'.
Hope this helps

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
What Indu said is correct.I would like to add one more thing to it If the static keyword is removed before the block,the print statement will be executed each time a instance of that class is created and not when the class is loaded.Then answer B will be correct.
 
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer is C, since static initializers are executed only when the JVM loads the class.
-- Sandeep
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
What Jitender says makes sense, since each time an object is created it has to initialize its instance varaibles.The instance initializer block ({}) is just like a instance variable for the object.
-- Sandeep
SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)
 
reply
    Bookmark Topic Watch Topic
  • New Topic