0

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.

Junaid
  • 1,668
  • 7
  • 30
  • 51
  • Actually strings are immutable, so are the primitive wrapper types. – Elliott Frisch Jul 22 '14 at 06:31
  • 1
    You are wrong, there are no special cases. Why do you think your second example differs from your third? – Boris the Spider Jul 22 '14 at 06:32
  • (I like to avoid thinking about "memory locations" or "pointers".. leave those in C. At the low-level case, simply consider that a reference *value* is an *opaque identifier* representing an object.) – user2864740 Jul 22 '14 at 06:32
  • Yes. But I have checked with StringBuilder object, Integer objects...they all behave like above. – Junaid Jul 22 '14 at 06:32

1 Answers1

1

For :

String str1 = "myString";
String str2 = str1; // Both pointing to independent memory locations. NO!
str1 = null; // Only str1 gets null

Consider this example :

public static void main(String[] args) {
        String s1 = "hello";
        String s2 = s1;
        System.out.println(s2 == s1); // true . Both pointing to same location
s1=null; // s2 still points to "hello"

    }
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • I think, you are right. s1 just starts pointing to new memory location, which happens to be NULL, in this case. – Junaid Jul 22 '14 at 06:36
  • 1
    *s1 just starts pointing to new memory location, which happens to be NULL* is kind of *incorrect*. s1 doesn't actually point to a *new location which is null*, it actually points to *null* which is nothing at all. :) – TheLostMind Jul 22 '14 at 06:42
  • @Junaid - BTW, *obj1 = null; Both obj1, and obj2 get NULL* is also *incorrect*, only obj1 will be null , obj2 will not be null. – TheLostMind Jul 22 '14 at 06:45