I have seen this snippet in SCJP form on ranch. But i have confusion.
public class GarbageTest {
GarbageTest g;
int a = 5;
public GarbageTest(Object obj) {
this.g = (GarbageTest) obj;
System.out.println(this.g);
}
public static void main(String[] args) {
GarbageTest gb1 = new GarbageTest(null);
System.out.println(gb1.a);
}
}
Here the instance variable g is assigned a null in the constructor.
But still i can access the variable a. That is last line in the main() prints 5.
How it is? Can anybody explain please.
You still have access to the variable a at the end of the main method. Yes. Why shouldn't you? It doesn't make any difference that you passed null; the gb1 reference and that variable are still there. You are confusing passing null to the constructor and setting the gb1 reference to null.
In fact, you have to pass null somewhere to that constructor to avoid endless recursion and a stack overflow problem
You still have access to the variable a at the end of the main method. Yes. Why shouldn't you? It doesn't make any difference that you passed null; the gb1 reference and that variable are still there. You are confusing passing null to the constructor and setting the gb1 reference to null.
In fact, you have to pass null somewhere to that constructor to avoid endless recursion and a stack overflow problem
Hello Mr Campbell
I didnt get the overflow , how would overflow occur if null wasnt passed .
Can you please explain in the same example
Abimaran Kugathasan wrote: . . . OK, What would happen if you code like below? . . .
Exactly the sort of thing I meant. And, Pratik D mehta, did you notice I didn't post "a stack overflow problem", but "a stack overflow problem"? Did you read the link?
Oh, that was your question I was referring to in the first place.
If you don't pass null, you have a second GarbageTest object, which you pass a 3rd GarbageTest object, and that requires a 4th GarbageTest object, and that requires a 5th . . . .
Abimaran Kugathasan wrote: . . . I don't see anyone with this name here!
You should see the way they misspell other people's names. Or call the women "Sir".
Pratik D mehta, please be careful; it is often regarded as rude to spell somebody's name wrongly, when it is visible written. Use copy-and-paste for names as well as for code.
Hey.. Yes I was confused because of null.
Although I'm accessing the variable 'a' through gb1 which is not null and g is null. So NullPointerException kicks me if I use 'g' to access 'a'.
Thanks guys... One question has led another with answer.. Great...
I also apologize to Campbell Ritchie . I guess I was confused at that time and thinking many things . I got things wrong .
I Respect the help I get on this forum . All the people here are amazing and it feels very friendly.
Post by:autobot
He puts the "turd" in "saturday". Speaking of which, have you smelled this tiny ad?
a bit of art, as a gift, that will fit in a stocking