I am writing a static analysis tool for Java
programs. And during analysis of assignment operators, for example, I want to know if underlying objects are using copy-by-value or copy-by-reference.
In case of primitive data types, I know, variables use copy-by-value.
int x = 5;
int y = x; // Both are pointing to independent memory locations.
In case of objects, usually they copy reference value of other objects. For example,
MyClass obj1 = new MyClass();
MyClass obj2 = obj1; // Both instances pointing to the same memory location.
However, in special cases, such as
String str1 = "myString";
String str2 = str1; // Both pointing to independent memory locations.
str1 = null; // Only str1 gets null
Objects use copy-by value, in my opinion. Please correct me if I am wrong. Similarly, StringBuilder
and other java/lang/*
classes that are declared with final
keyword, their objects/instances behave like that. However, when being passed as parameter to a method, their reference values are passed.
So my question is that is there any way to find all such special cases where objects always use copy-by-value behavior? How can I find all such classes? This may not be an easy task, any kind of suggestion is welcome. Thanks.