Hi all! In the following code I am passing a String Object to method calc and as its an Object I presume its a pass by Reference scenario and the toUpperCase function should work on the original value..but it doesn't..?? I then wrote a simple Pi class which has a member variable valueand modifications to it work in the expected way, as in changing the original. Can anyone just tell me why passing String Object doesn't seem to be done by Reference? Thanx in advance
(edited by Cindy to format code) [ June 12, 2002: Message edited by: Cindy Glass ]
So you have a variable that points to a lower case String. Then you pass a copy of that reference into a method. The local variable bbbb now has a reference to the lower case String. You call the toUpperCase method, which returns a reference to an Upper Case version of the string, and you put THAT reference in the local variable bbbb. No where did you change the reference that the original variable was looking at. It is still referencing the lower case String. Since Strings are immutable, you can not actually CHANGE the String object that is being referenced. All you can do is change what the variable is pointing at.
"JavaRanch, where the deer and the Certified play" - David O'Meara
When you pass the reference to the string and modify it in the method it doesn't affect the calling object, in essence creates a new string. When you are passing PI value, the value gets changed since there are could be no other instance of this field (java.lang.Math) since it is declared as "public static final double PI" in java API, so there only one, value of which you are changing in your "calc" method. [ June 12, 2002: Message edited by: Irene Loos ]
You are coming from C(++) I presume? Java objects are more like pointers than C++ references. When you pass around an object, you are passing around a pointer to its location in memory. Changing the value of a copied pointer won't change the original one.
Thanks I found that article very helpful,Guess if I had used a StringBuffer initially I wouldn't have been so confused but I gained a better understanding. For anyone interested, I changed my code as below for testing passing references.