0

I want to update java.sql.Timestamp in other method. But it is not updated in main method. Why? Is that passed by value or reference?

package test;

import java.sql.Timestamp;
import java.util.Date;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        Timestamp a = null;
        Date now = new Date();
        Timestamp b = new Timestamp(now.getTime());

        update(a, b);
        System.out.println(a); // returns "null", why?
    }

    /**
     * Sets the newer timestamp to the old if it is possible.
     * @param a an old timestamp
     * @param b a new timestamp
     */
    private static void update(Timestamp a, Timestamp b) {
        if(b == null) {
            //nothing
        } else if(a == null) {
            a = b;
        } else if(a.after(b)) {
            a = b;
        }
    }
}
Peter
  • 42
  • 8
  • possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Jonathan Feb 11 '15 at 08:50

1 Answers1

2

Java uses CallByValue. That means that the value is transfered to the methos not the reference to the object. So a will only changed inside you function.

If you would like to change it in `main function you have to get it back via return value.

package test;

import java.sql.Timestamp;
import java.util.Date;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        Timestamp a = null;
        Date now = new Date();
        Timestamp b = new Timestamp(now.getTime());

        a = update(a, b);
        System.out.println(a); // returns "null", why?
    }

    /**
     * Sets the newer timestamp to the old if it is possible.
     * @param a an old timestamp
     * @param b a new timestamp
     */
    private static Timestamp update(Timestamp a, Timestamp b) {
        if(b == null) {
            //nothing
        } else if(a == null) {
            a = b;
        } else if(a.after(b)) {
            a = b;
        }

        return a;
    }
}
Jens
  • 67,715
  • 15
  • 98
  • 113