Why doesnt this String change?

S

SlowLearner

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;
}
 
J

John Ersatznom

SlowLearner said:
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;
}

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.)
 
S

SlowLearner

SlowLearner said:
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;
}

Thanks for your help everybody
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top