1

on passing object reference to static method m1() why it does not become null and why last statement doesn't give errror. Output is X

 class I {
        private String name;
        public String name() {            
            return name;
        }
        public I (String s) {            
            name = s;            
        }
    }

    class J {
        public static void m1 (I i){
            i = null;
        }
        public static void main (String[] arg)
        {
            I i = new I("X");
            m1(i);
            System.out.print(i.name());
        }
    }
Aman J
  • 1,825
  • 1
  • 16
  • 30
rg665n
  • 163
  • 1
  • 8
  • Please edit your question to have a sensible *title* and then text within the question. Questions which are *just* code are pretty poor... – Jon Skeet Aug 22 '12 at 18:41
  • (I've performed an edit to make things somewhat more reasonable, but you should edit it further yourself.) – Jon Skeet Aug 22 '12 at 18:44

3 Answers3

1

Java is pass by value (Read second answer in the link specially)

I i scope of i is limited to method m1 only.

In execution it looks something like:

`I i` in `m1()` points to `null` reference

I i method reference still points to `new I("X");`
Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
1

Java is pass by value so scope of i is limited to m1()

public static void m1 (I i){ // i is copied from i which is in main method but it is another variable whose scope lies within m1() only

    i = null;  // original i in main lies in main() method scope

}

If you change name of i in method m1(), confusion will be lesser like :

public static void m1 (I iObj){ 
    iObj = null;  // i in main() method still points to Object

}
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
1

Java uses pass by value exclusively. Changing the value of i within m1 only changes that parameter's value. It doesn't do anything to the variable i within main.

What may confuse you - it certainly confuses plenty of other people - is that although the arguments are passed by value, if the type of the parameter is a class, then that value is a reference... and indeed the value of the i variable in each case is a reference. That reference is still passed by value - the value of the argument is directly copied as the initial value of the parameter. However, if instead of changing the parameter itself you make a change to the object that the parameter value refers to, that's a different matter:

void foo(StringBuilder builder) {
    builder.append("Hello");
}

void bar() {
    StringBuilder x = new StringBuilder();
    foo(x);
    System.out.println(x); // Prints Hello
}

See the Java tutorial on passing information to a method or constructor for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194