1. A code fragment that is interesting & confusing public static void main(String[] args) { String x = new String("ab"); change(x); System.out.println(x); } public static void change(String x) { x = "cd"; } It prints "ab". In C++, the code is as follows: void change(string &x) { x = "cd"; } int main(){ string x = "ab"; change(x); cout << x << endl; } it prints "cd". 2. Common confusing questions x stores the reference which points to the "ab" string in the heap. So when x is passed as a parameter to the change() method, it still points to the "ab" in the heap like the following:
Read full article from String is passed by “reference” in Java
No comments:
Post a Comment