• Post Reply Bookmark Topic Watch Topic
  • New Topic

Re: Change String value in method call  RSS feed

 
Joe Cheung
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

I attempt to modify the String value using the code shown below:

String temp = "Before";
System.out.println("Output 1" + temp);
method(temp);
System.out.println("Output 2" + temp);

public void method(String a) {
a = "After";
}

I expected the 1st and 2nd line will print "Before" and "After" but the both lines displayed "Before"!!!

How can I change the value of variable "temp"?

Regards,
Joe
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't change the value of a local variable except by assigning to it from the method where it is declared. Read this and then this, and you'll understand why.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!