0
import java.io.IOException;
import java.util.ArrayList;

public class CheckClass {
    static ArrayList<String> curr2=new ArrayList<>();
    public static void main(String[] args) throws IOException
    {
    ArrayList<String> curr=new ArrayList<>();
    System.out.println(curr);
    CheckArr(curr);
    System.out.println(curr);
    }
    private static void CheckArr(ArrayList<String> curr) {
        curr2.add("hi");
        curr=curr2;
        System.out.println(curr);
    }
}

Its output is :

[]
[hi]
[]

Can anyone explain how i can change the reference of curr to curr2. I just switched from C++ to java. I think it has something to do with internal pointer mechanism of java, can you explain this concept.

Freez
  • 53
  • 9
  • Java is not like c where you can change the pointer to a new memory address. The closes think to that is if the curr2 would be a field member class. – dreamcrash Jan 15 '21 at 17:04
  • @dreamcrash Yeah that solved my question. but Is there no way in java by which above thing will be possible ? – Freez Jan 15 '21 at 17:13
  • No, Java is pass-by-value, you can't just change the paradigm of a programming language when it seems convenient. You can either return the reference, and assign it to `curr`, or you can expand the scope of `curr` to outside the method. – Charlie Armstrong Jan 15 '21 at 17:18
  • I mean, if you pass an array of objects, then you can change the object in one of the array positions. But doing like you did there is no way around it – dreamcrash Jan 15 '21 at 17:18

1 Answers1

0

In Java when you pass any Object to a function, the reference to this Object is passed by value. That's why, when you change the reference to the Object, it will change only in function.