0

I'm pretty new to Java and I would like the following function to change the source variable.

public class DummyClass {
    public void str(String str) {
        str = "";
    }
}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "strstr";
        DummyClass classy = new DummyClass();
        classy.str(str);
        System.out.print(str);
    }

}

it prints "strstr" and I would like it to print nothing.

  • Cannot be done. Java strings are immutable. You can't change them, ever. – markspace May 31 '15 at 18:56
  • 1
    @markspace Even if it was not immutable it would change nothing, as the reference is passed by value. – Alexis C. May 31 '15 at 18:57
  • Not sure exactly what you are asking, but here goes: rather than hard-code the String, pass the value as a command line argument and change the code to use the passed argument (via `args`) – copeg May 31 '15 at 18:59
  • @markspace *"You can't change them, ever"* are you sure about that? ;) ... https://github.com/tonymorris/java-trivia/blob/master/src/MutableString.java :D – Tom May 31 '15 at 19:36
  • If you use reflection like that, you break everything, including thread safety and the Java security model. No sane installation will let you do that. (You can hack a development environment to allow you to change strings, but good luck getting anyone to agree to this in production code.) – markspace May 31 '15 at 19:40
  • @markspace If you should do that or if someone else would allow that, is a different question. I just wanted to show that *"you can't change them"* isn't _completely_ true. – Tom May 31 '15 at 19:53

0 Answers0