Sunday, July 21, 2013

java pass-by-value v.s. pass-by-reference

 

package cci_chap1_arrayString;

public class RemoveDuplicate {
    String removeDuplicate(String p_str)
    {
        int len = p_str.length();
        for (int i=0; i<len; i++)
        {
            for (int j=i+1; j<len; j++)
            {
                if (p_str.charAt(j)==p_str.charAt(i))
                {
                    p_str = ((new StringBuilder(p_str)).deleteCharAt(j)).toString();
                    j--;
                    len--;
                }
            }
        }
        return p_str;
    }
    public static void main(String[] args)
    {
        String str = "abbbecettt";
        RemoveDuplicate rdObj = new RemoveDuplicate();
        String resString = rdObj.removeDuplicate(str);
        System.out.println(resString);
    }

}

http://stackoverflow.com/a/8528764/2041023

 

When passing an Object variable to a function in java, it is passed by reference. If you assign a new value to the object in the function, then you overwrite the passed in reference without modifying the value seen by any calling code which still holds the original reference.

However, if you do the following then the value will be updated:

public class StringRef
{
public String someString;
}

static void f(StringRef s)
{
s.someString = "x";
}

public static void main(String[] args)
{
StringRef ref = new StringRef;
ref.someString = s;
f(ref);
// someString will be "x" here.
}

http://stackoverflow.com/a/40523/2041023