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); } 
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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; } 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.