Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default constructor

 
Rama Raju
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class AQuestion
{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
In the above example, it is printing 0. Can u explain how zero is getting printed?
 
Javix Protocol
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Study the basics clearly and then put the question.
Try Simon Roberts "The Complete Java2 Certification Study Guide"
buddy.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try making int j = 10 as static int j= 10. This should print 10 instead of 0.
I think this also explains why it's printing 0.
Prabhu.
 
Rama Raju
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Javax Protocal,
Thanx for your suggestion.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just by re-arranging the order of declaring int i and int j will give you the result 10. Try the following code:
<pre>
public class AQuestion
{
private int j = 10;
private int i = giveMeJ();
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
</pre>
Reason:
12.4.1 of the JLS says A class or interface type T will be initialized at its first use, which occurs if ...
"A non-constant field declared in T (rather than inherited from a superclass or superinterface) is used or assigned."
When an instance of the class is created, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values. It means i = 0 and j = 0 when the object is first created.
(In your version)
The assignment statement i = giveMeJ() then starts the initialization process. At that stage, j has not been initialized. It means j is zero, therefore giveMeJ() returns zero to i. So i is assigned a zero again. Next, j is initialized to 10. That's why it prints a 0, not 10.
(In my version)
The assignment statement j = 10 is the first assignment statement, so j is assigned 10. Then the statement i = giveMeJ() assigns the current value of j (10) to i. So the program prints 10.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic