Page 2 of 2
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Wed Dec 25, 2019 3:24 am
by admin
There is only one variable named obj in the given code and that variable is declared at line //1. So, I am not sure what is the confusion about the variable.
Please remember that variable and the object to which it points are two different things.
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Wed Dec 25, 2019 4:53 am
by morarumaria1988
It's clear now, thanks!
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Thu Jan 30, 2020 3:44 pm
by demetrio
Suppose the question code was (I just added one println line):
public class NewClass {
private Object o;
void doSomething(Object s){
o = s;
//line bellow was added
System.out.println("the second time this line is printed is the exact moment "
+ "when the object created in line 1 can be Garbage Collected"); //line 7
}
public static void main(String args[]){
Object obj = new Object(); // 1
NewClass tc = new NewClass(); //2
tc.doSomething(obj); //3
obj = new Object(); //4
obj = null; //5
tc.doSomething(obj); //6
}
}
Am I right? I mean, the second time line 7 is evoked is the exact moment where the object created in line 1 is eligible for garbage collector, right?
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Thu Jan 30, 2020 5:54 pm
by admin
Correct.
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Wed Sep 08, 2021 1:19 pm
by qazwsx922
How do I know line5 makes obj(on line 4) null?,instead of line 1 obj?
I thought line 5 made line1 obj null.
Re: About Question enthuware.ocajp.i.v7.2.920 :
Posted: Wed Sep 08, 2021 1:54 pm
by admin
The code given in the question is:
Code: Select all
Object obj = new Object(); // 1
NewClass tc = new NewClass(); //2
tc.doSomething(obj); //3
obj = new Object(); //4
obj = null; //5
tc.doSomething(obj); //6
obj is being reassigned a new Object at //4, that means the statement obj = null; at //5 will cause that Object to lose the reference.