• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with output

 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
{ 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
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, I got it now..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic