• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Static  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When is the text "Hi there" displayed?
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() ;
}
}

a) Never.
b) Each time a new object of type StaticTest is created.
c) Once when the class is loaded into the Java virtual machine.
d) Only when the main() method is executed.

is it D or D ? can anyone explain briefly
 
Gauri Telang
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
correction - i meant is it C or D?
 
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answer is C.

To understand better run the following code, which I modified your code little bit:

public class StaticTest {

public static void main(String args []) {
Tester st1 = new Tester() ;
st1.print(1) ;
Tester st2 = new Tester() ;
st2.print(2) ;
}

}

class Tester{
static {
System.out.println("Hi there") ;
}

public Tester() {}

public void print(int i) {
System.out.println("Hello " + i) ;
}
}
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gauri,

Static Intializer blocks & expressions are executed only once & when class is loaded.
Also "Hi there" will be the first statement to be printed.

Thanks
Gagan.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!