• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 140
  • Last Modified:

a String as an argument to a method

Hello,
I don't understand why, in the code below, the String st is not affected by the call to the method cutString(st).
Any explanations are welcome.
Tks,
Stéphane


class TestString {


      TestString() {

      String st = "coucou";
      cutString(st);

      System.out.println("In constructor: st= "+st);
      }

public static void main(String[] arts) {
      new TestString();


}

void cutString(String s) {

s = new String("hello");
System.out.println("In method: s= "+s);
}

}
0
st5
Asked:
st5
  • 2
1 Solution
 
mbormannCommented:
stephane,
see the thing is that when the constructor calls the method cutString(s) in Java u always pass references so if u print this string like this
System.out.println("In method: s= "+s);
before u do
s = new String("hello");
then u will see that the string is "coucou" but then you allocate a New string  and store the location of that string in 's' which nows points to that location in Memory which is having the string "hello".

the original refrence to "coucou" is now lost and that part of memory is a candidate for Garbage collector.
0
 
mbormannCommented:
Oops ,I didnt see the rest of ur constructor the string reference 'st' will be lost after the constructor has finished initialising the TestString object.

if u have any more string related questions pls ask.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now