Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!