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

Help plz..

 
Vijayakumar Ramakrishnan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
Please explain the output of this program.
inside method 00
inside method 1010
10
10
Vandanam,
vijay
public class bb
{
int i = amethod();
int j=10 ;
private bb()
{ int i=100; }
public int amethod()
{
i=j;
System.out.println("inside method " + i + j);
return j;
}
public static void main(String args[])
{
bb b=new bb();
int c = b.amethod();
System.out.println(c);
System.out.println( b.i);
}
}

 
Sivaram Ghorakavi
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's simple variable initialization..
when the class first intantiated the variable initialization takes place. In this case i = aMethod()--> aMethod is called. Since the default value of i and j are still 0 in aMethod the same is printed. Then j gets 10 and bb.aMethod() returns i=10 (since j is already 10 by now) returns 10;
Hope this helps...
This has been discussed in this group try to search on this topic and you get some good links too.
BOL
 
Rajiv Ranjan
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vijay ,
Let me try to explain this:
The output of the program is
inside method 00
inside method 1010
10
10
There should be no confusion about last two lines as they are the output of System.out.println (last two lines of your programm).

Lets take a look at the output :
inside method 1010
This is output of the statement :
int c = b.amethod();
of your programm , as you are calling amethod and it has a System.out.println statement.

The other output :
inside method 00
is because of what you call a forward reference.
When you created a instance of class , by the following statement
bb b=new bb();
the compiler loads the class and tries to initialize the member variable.You have initialized the variable i as
int i = amethod();
as a result of which amethod is called at the class loading time.The compiler sees the statement i==j in amethod , but since variable j is still not initialized it is assigned a default value i.e 0 and hence a output of 00 is printed.
Check the following link for for explanation on forward reference
http://www.javaranch.com/maha/Discussions/Declaration_And_Access_Control/Another_qstn_for_you_all____Just_to_enforce_the_point___-_JavaRanch_Big_Moose_Saloon.htm
Hope I have not confused you more.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic