This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explanation of Code

 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test1
{
static int k=1;
{
k=k*2;
}

public static void main(string args[])
{
System.out.println(k);
}
}

The output is 1 but i think it must be 2. How is it so? Please help me.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

instance blocks will run just before constructor.
There is no constructor call. and so is instance block call.
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Gaurav Pavan Kumar Jain

{
k=k*2;
}
This is an instance block means when ever you create an instance of that class this code will be executed ,but before completion of execution of constructor
here in your case your not creating the object of that class.
If you have doubt create the object of that class,then you will come to know
 
Chris Jebaraj
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gaurav,

Your output is correct. It should be 1. Because the code block k=k*2; is not put inside a static block. Its just a normal block. Your static declaration of k is ended with ;

If you want your output to be 2, then your code must be,
 
Chris Jebaraj
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As srinivasan said, you havent called the constructor. If you want the k=k*2 as a instance block and not a static one, then your code should be

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic