Java string value change in function

Viewed 48061

I have this very awkward question...

void changeString(String str){
    str = "Hello world":
}

main(){
    String myStr = new String("");
    changeString(myStr);
}

When main returns, the value is still "" and not "Hello world". Why is that?

Also, how do I make it work? Let's say I want my function changeString to change the string it got to "Hello world".

7 Answers

Bill, I have a solution to your problem which uses a List as a pointer in java!

void changeString(List<String> strPointer ){
    String str = "Hello world";
    strPointer.add(0, str);
}

main(){
    LinkedList<String> list = new LinkedList<String>();
    String myStr = new String("");
    changeString(list);
    myStr = list.get(0);
    System.out.println( myStr );
}

This answer takes a little extra work to insert and get out the string from the list, however the final line will print "Hello world!"

I hope this can help others as well!

-Port Forward Podcast

Here's the one more solution by StringBuffer/StringBuilder worked for me.

static void changeValue(StringBuilder str){
    str.append("newValue");
}

main(){
    StringBuilder originalVal= new StringBuilder();
    changeValue(originalVal);
    System.out.println(originalVal.toString());
}
Related