Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi, The below program behaves

Status
Not open for further replies.

kris727

Programmer
Nov 2, 2000
4
US
Hi,
The below program behaves as follows. As it is, it prints the object value of "it" within the function g() as some valid value. Once I replace the commented //it.g() and make it uncommented and comment the next line g(), the value of "it" is null. can some one explain me this behavior ?


thanks,
krishna


import java.io.*;
import java.util.*;


public class InstanceTest {

InstanceTest it;


public void f() {

it = new InstanceTest();
System.out.println("it value is " + it);
//it.g();
g();
}

public void g() {

System.out.println("it value is " + it);


}

public static void main(String[] args) {

InstanceTest it1 = new InstanceTest();
it1.f();


}

}

 
Sure,

1) it.g();
Your initializing the InstanceTest variable 'it' within the scope of the InstanceTest.f() method. It's 'it' member is initialized to null by the VM.

Then you call the member variable's .g() method (it.g();)which outputs the value of his .it member which (as we just stated) is null.

2) g();
Your initializing the InstanceTest member variable 'it' within the scope of the InstanceTest.f() method. Then you call your own .g() method ( g();) which outputs the value of your own .it member which (as we just stated) we just initialized to a valid object ( = new InstanceTest()).

Simple eh?

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top