I'm trying to create a method which returns a flag and a string. So I
passed the String as an argument but it doesn't change. I thought all
objects were past as references and so I could change the value. What
am I doing wrong?
SomeEvent(....) {
String FolderName="123";
if (test(FolderName)) Do SomeThing;
// FolderName still 123 at this line. Why isn't it asdfg?
}
public boolean test(String txt) {
txt="asdfg";
return true;
}
> I'm trying to create a method which returns a flag and a string. So I
> passed the String as an argument but it doesn't change. I thought all
[quoted text clipped - 11 lines]
> return true;
> }
The line
txt="asdfg";
is assigning a String object "asdfg" to the reference "txt", but doesn't
change the reference "FolderName". The references themselves aren't
passed by reference. :)
If you invoked a method on txt that altered its contents, it would
affect FolderName. But Java strings are immutable, so this isn't
possible. To do what you want you need StringBuffer:
StringBuffer FolderName = new StringBuffer("123");
...
public Boolean test (StringBuffer txt) {
txt.delete(0, txt.length());
txt.append("asdfg");
return true;
}
FolderName now also points to "asdfg" after test(FolderName) is called.
(On the other hand, "txt = new StringBuffer("asdfg");" wouldn't work. It
would change "txt" to refer to a different StringBuffer, rather than
change the StringBuffer itself.)
> I'm trying to create a method which returns a flag and a string. So I
> passed the String as an argument but it doesn't change. I thought all
[quoted text clipped - 11 lines]
> return true;
> }
Thanks for your help everybody