1

I have this piece of code. Why do I get "DOG" if the object is null? Is it not been, in this case given reference?

static void met1(Object ob) {
    ob = null;
}

public static void main(String[] args) {
    String a = new String("dog");
    met1(a);
    System.out.println(a);
}
g3245457
  • 21
  • 2

3 Answers3

2

When calling the method met1 you are actually passing a copy of your reference to the method, because of that changing the copied reference wont affect the original reference value.

Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44
1

When met1 method is called, Copy of reference a is passed. Stack frame of met1 method will have a's reference address and now it is addressed as ob. When changing the value of ob to null makes the reference varaible as null. During the exit of the method all these parameter value will destroy and the original main method still have the original reference pointed to a. If null value should be returned from met1 method then code should be modified as below

          a=met1(a)

         static String met1(Object ob)
         {
         return null;
         }
Mohan Raj
  • 1,104
  • 9
  • 17
0

Pass by reference will not affect the original reference which is passed by.