Two Laptop Bag
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with output" Watch "Problem with output" New topic

Problem with output

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274

class tt {
static String s = "-";

public static void main(String[] args) {
{ 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.

Praveen Javvaji

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.

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,


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

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:
subject: Problem with output
It's not a secret anymore!