jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static" Watch "Static" New topic
Author

Static

Gauri Telang
Greenhorn

Joined: Jun 29, 2004
Posts: 13
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

Joined: Jun 29, 2004
Posts: 13
correction - i meant is it C or D?
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Aug 23, 2005
Posts: 47
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static