0

I'm not sure if the title is the best, but what I want to do can be illustrated in this example

class TestClass {
    public String foo = "foo"

    public void makeFooBar() {
        String bar = foo;
        bar = "bar";

        System.out.println(foo); //should print "bar"
    }

}

This is obviously a contrived example, but it illustrates the point. I want to change the value of foo by changing the value of bar that references foo. is that posible?

richbai90
  • 4,994
  • 4
  • 50
  • 85

1 Answers1

1

This could be a way if you want to update a certain value in multiple places (e.g. by using a wrapper object). Of course there are waay more fancier ways to accomplish something simular.

class TestClass {
    public Wrapper<String> foo = new Wrapper("foo");

    public void makeFooBar() {
        Wrapper<String> bar = foo;
        bar.set("bar");

        System.out.println(foo); //should print "bar"
    }

     public static class Wrappper<T>
    {
          T value;

         public Wrapper(T value)
         {
               this.value = value;
         }

         public T get() { return this.value; }
         public void set(T newValue) { this.value = newValue; }
         @override
         public String toString() { return value.toString(); }
    }
}

Basically any primitive type cannot be passed by reference. Althoug String is technically not a primitive type, java does treat it a bit more special. (Reading upon Internal Stringpool would give you a nice insight. In this page there is a nice explanation including some visual examples: http://www.journaldev.com/797/what-is-java-string-pool)

n247s
  • 1,898
  • 1
  • 12
  • 30