aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explanation of Code 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 "explanation of Code" Watch "explanation of Code" New topic
Author

explanation of Code

Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
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

Joined: Feb 15, 2007
Posts: 557
Hi,

instance blocks will run just before constructor.
There is no constructor call. and so is instance block call.


Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447
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

Joined: Sep 19, 2003
Posts: 34
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,


JebaRaj.<br /> MCP, SCJP 1.5 <br />----------------------------<br /> THOUGH TIMES TEACH TRUST. <br />----------------------------
Chris Jebaraj
Ranch Hand

Joined: Sep 19, 2003
Posts: 34
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

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explanation of Code