wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help plz.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help plz.." Watch "Help plz.." New topic
Author

Help plz..

Vijayakumar Ramakrishnan
Greenhorn

Joined: Dec 16, 2000
Posts: 24
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

Joined: Nov 30, 2000
Posts: 56
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

Joined: Sep 28, 2000
Posts: 61
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.
 
 
subject: Help plz..