0

Here is the program

public class Closure {

     public String foo = "";

     public static Closure process(final Closure t) {
          System.out.println(t.toString() + " = " + t.foo);
          t.foo = "bar";
          new Runnable() {
             public void run() {
                System.out.println(t.toString() + " = " + t.foo);
                t.foo = "baz";
             }
          }.run();
          System.out.println(t.toString() + " = " + t.foo);
          return t;
     }

    public static void main(String[] args) {
       process(new Closure());
    }

}

When I execute it, all 3 prints show the same reference for the variable t.foo. This makes sense for Closures, it is as we expect it.

What puzzles me is that in Java Strings are immutable. So if we reassign the string, shouldn't the reference change?

Ankit Bansal
  • 4,962
  • 1
  • 23
  • 40
Pavan Kemparaju
  • 1,591
  • 3
  • 16
  • 25
  • 1
    Did you try to reassign it to see what happens? Where is you engineering spirit? – Edwin Dalorzo May 19 '14 at 12:40
  • 1
    What do you mean by "shouldn't the references change"? Shouldn't *which* references change? I suspect you're confused about what the immutability of String really means. – Jon Skeet May 19 '14 at 12:41

3 Answers3

1

It is a little confusing to be using Closure when the question doesn't contain any closures.

The output of your program should look like (Ideone wants a class with this name instead of Closure)

Ideone@1e61582 = 
Ideone@1e61582 = bar
Ideone@1e61582 = baz

see http://ideone.com/c5HzEF

As you can see the reference foo is changing. The reference t which is what you print, doesn't change as expected.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

No, because you print the reference of the Closure object, not of the String.

Smutje
  • 17,733
  • 4
  • 24
  • 41
0

The foo property is a reference. This is a misunderstanding of what it means for a string to be immutable in Java.

See Immutability of Strings in Java

Community
  • 1
  • 1
Chris Lear
  • 6,592
  • 1
  • 18
  • 26