• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static

 
Gauri Telang
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?
 
Kj Reddy
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) ;
}
}
 
Gagan Deep
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic