Code: Select all
Holder link;
public Holder(int val){ this.value = val; }
public static void main(String[] args){
final Holder a = new Holder(5);
Holder b = new Holder(10);
a.link = b;
Moderator: admin
Code: Select all
Holder link;
public Holder(int val){ this.value = val; }
public static void main(String[] args){
final Holder a = new Holder(5);
Holder b = new Holder(10);
a.link = b;
admin wrote:link is a field in class Holder. a is a variable of class Holder. So a.link refers to the member field link of the Holder object pointed to by a.
b is another variable of class Holder. It also points to an object of class Holder.
Therefore, in a.link = b; you are assigning the object pointed to by b to a.link.
I hope that explains it.
Regarding toughness, you are right. It doesn't look like an easy question
HTH,
Paul.
Code: Select all
public static Holder setIt(final Holder x, final Holder y){
x.link = y.link; //makes a.link to null so now a is an object with value=5, link = null
return x; //returns a. This is important because it is being assigned to b. So b.link.value gives a.value, i.e. 5 because of this return statement.
}
Code: Select all
class Holder{
int value = 1;
Holder link;
public Holder(int val){ this.value = val; }
public static void main(String[] args){
final Holder a = new Holder(5);
Holder b = new Holder(10);
a.link = b;
b.link = setIt(a, b); //(1)
System.out.println(a.link.value+" "+b.link.value);
}
public static Holder setIt(final Holder x, final Holder y){
x.link = y.link; //(2)
return x; //(3)
}
}
You need to understand that accessing a null reference always causes a NullPointerException to be generated. Always. No exceptions.NickWoodward wrote:I got the question right, so think I understand the main points, but....
I can't see why trying to access a.link.value would through an NPE. Yes it's null, but
String s = null; System.out.println(s); doesn't throw that exception.
I thought it might be applying the + operator, but it also occurs with System.out.println(a.link.value);
does that make sense?
thanks,
Nick
No, a.link = b does not mean a.link = b.link. It means a.link points to the same object to which b is pointing.bniky1 wrote:I have read the previous comments and still don't understand a.link = b. Does this mean a.link = b.link?
Users browsing this forum: No registered users and 20 guests