Setting equal in Java: by value or reference?

前端 未结 4 1750
长发绾君心
长发绾君心 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 00:41

    Everything in java is passed by Value.There nothing like pass by refrence in java.Objects reference is passed by value. in ist case ie

    String str1="old"
    String str2=str1; //here str2 is pointed to str1
    str1="new";       // here link of str1 is broken with old and pinted to new location      where as str2 is pointing to same location as earlier.
    

    While in case of list both list are pointing to same memory location so changes are reflected.

提交回复
热议问题