Page 1 of 1
About Question enthuware.ocajp.i.v7.2.988 :
Posted: Tue Apr 29, 2014 2:20 pm
by madman0817
I am probably wrong here, and am not good with wording, but, sb is declared in main, and 's' in stringBuilderTest is 'declared' in it's method, so, how is the method able to change the variable outside of it's local declaration? Is this sending a variable by reference? So confused.. I would think that you should need something like sb = stringBuilderTest(sb);
edit: Meaning, sb is an instance variable, not a member variable, right?
Help?
Re: About Question enthuware.ocajp.i.v7.2.988 :
Posted: Tue Apr 29, 2014 9:15 pm
by admin
sb is indeed a local variable. But the objects created using new are always created on "heap", which is a common memory area for the whole program. So when you pass sb to stringBuilderTest, the address to the same StringBuilder object is passed to the method and that method operates on the same instance.
"instance variable" and "member variable" are two names for the same thing. "sb" is neither of them. sb is a local variable, also known as "automatic variable".
You should go through
http://www.javaranch.com/campfire/StoryCups.jsp and then
http://www.javaranch.com/campfire/StoryPassBy.jsp for a clear understanding.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.988 :
Posted: Wed Apr 30, 2014 3:09 pm
by madman0817
wow, that was a great example, thanks.
Re: About Question enthuware.ocajp.i.v7.2.988 :
Posted: Tue Feb 07, 2017 4:10 pm
by jamesmccreary
I believe since we are passing in a reference variable instead of a primitive variable, the same "object" within the main method and the stringBuilderTest method is being manipulated by the stringBuilderTest method, yes?
Would therefore the following two versions of stringBuilderTest be equivalent?
Code: Select all
//Original
public static void stringBuilderTest(StringBuilder s) {
s.append("o");
}
//My modification
public static StringBuilder stringBuilderTest(StringBuilder s) {
StringBuilder sbToReturn = s.append("o");
return sbToReturn;
}
Re: About Question enthuware.ocajp.i.v7.2.988 :
Posted: Thu Jul 05, 2018 2:48 pm
by mgb9987
Code: Select all
public static void stringTest(String s){
s= s.replace('h', 's');
}
why s=s.replace() is same as s.replace() here.
I tried this code. But o/p is same for both. Why???
In stringTest() method "s=s.....()" changed the value of the String but not in main() method.
Re: About Question enthuware.ocajp.i.v7.2.988 :
Posted: Thu Jul 05, 2018 10:44 pm
by admin
Two things:
1. Strings are immutable. So, replace doesn't change the original string. It creates a new one with the changes.
2. Java uses "pass by value" for passing parameters and returning results. This is a fundamental concept and you need to read about it from a good book (or online articles) to understand why assigning a new value to a method parameter doesn't affect the original parameter that was passed to the method.