Sunday, November 28, 2010

Passing parameters in a method

Always remember in Java, there's only pass by value. Pass by reference does not exist, full stop.

class A{
public static String commonStore = null;

static void keepCheckingIfValueIsNotNull(String value){
while(true){
if(value!=null) {
break;
}
else S.o.p("loop continues");
}
}
}
class B{
//lets do a call to check commonStore.
keepCheckingIfValueIsNotNull(A.commonStore);
A.commonStore = "string";
}

Will the above break the loop. It will not because, we're only passing the value of the variable, not the reference, itself.
To make this work, we should:
if (A.commonStore!=null) break;

So, what's the confusion. That's next.

0 Comments:

Post a Comment

<< Home