Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2006

Tip: Looking for answers? Try searching our database.

Why doesnt this String change?

Thread view: 
SlowLearner - 16 Dec 2006 22:14 GMT
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;
      }
John Ersatznom - 16 Dec 2006 23:12 GMT
> 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.)
SlowLearner - 18 Dec 2006 20:01 GMT
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.