aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with output" Watch "Problem with output" New topic
Author

Problem with output

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Given:

class tt {
static String s = "-";

public static void main(String[] args) {
go();
System.out.println(s);
}
{ go(); }//line a
static { go(); }
static void go() { s+= "s"; }
}
What is the output?

Ans is -ss

Doubt: I'm confused as to why not the line a code is not executed. please help.

Gitesh
Praveen Javvaji
Greenhorn

Joined: Dec 18, 2007
Posts: 4
Hi Gitesh,

You are invoking a static method in an initializer block, though the compiler won't complain, but the interpreter simply ignores it, it seems.

Try the following code,



Here the method is not static, so we can't invoke it from static initializer block, but we can invoke with an initializer block.

Hope this helps.

Praveen.
Ian Edwards
Ranch Hand

Joined: Aug 14, 2006
Posts: 107
{ go(); }//line a


This is a non-static initialisation block. This line isn't executed because no object is being instantiated. These blocks are only executed when an object is instantiated and are executed in the order that they appear.

In the case of the static initialisation blocks these are executed when the class is loaded.
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Hi Praveen,

thanks.

If i create an object of class tt (new tt() , in that case the initializer block gets executed. Like the code you mentioned will give o/p as:


I just wanted to know if the compiler will never complain of such initializer blocks where we aren't having a statement calling constructor or not?
Christian Hans
Greenhorn

Joined: Jan 08, 2008
Posts: 2
Ian Edwards provided the correct response. You execute non-static initialization blocks while creating an object. Adding the following to main will run the initialization block:

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
thanks, I got it now..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with output
 
Similar Threads
intiliazation blocks
why not output is helloworld
Static variables and inheritance
Garbage collection objects
Static blocks