Setting equal in Java: by value or reference?

前端 未结 4 1680
长发绾君心
长发绾君心 2020-12-17 00:29

I did two tests, the first starting with Strings

    String str1 = \"old\";
    String str2 = str1;
    str1 = \"new\";

    System.out.println(         


        
4条回答
  •  醉梦人生
    2020-12-17 01:03

    Java is all pass by value. There is no pass by reference with Java. A copy is passed to variables that could be method parameters or regular ordinary variables. Objects such as String literals, Strings, Array references, and ArrayLists will still pass by value.

    The thing is if the reference is not re-assigned then whatever happens to the reference variable will happen to the object it references.

    Check out this tutorial on this from the people that wrote head first java and other books here: http://www.javaranch.com/campfire/StoryPassBy.jsp

    Also with your code, OP, keep in mind that Strings are immutable. This means once the object is created it will not change basically. In your code though the String references are re-assigned while the List reference simply has a method called on it. The List references both point to the exact same ArrayList object; so the method call size() effects both List references since they both point to the same object in heap memory. :D

    Happy Coding!

提交回复
热议问题