Search code examples
javaandroidobjectnullcopying

Why Java code doesn't work when moved into a function?


I have a dummy Java function here. If p is a valid object, t should point to it.

private void turhake(Piece p, Piece t) {
    if (null == t && null != p) {
        t = p;
        if (null == t) System.exit(44);
    } else System.exit(43);
}

In the following code I ensure that the above function is only called if p is non null and t is null.

    if (threatener != null) System.exit(42);
    if (board[row][col] != null) {
        turhake(board[row][col], threatener);
        if (threatener == null) System.exit(41);
    }

The result should be that both p and t (board[row][col] and threatener) point to the same object. However my program exits with the code 41, indicating that t got nullified after the function call. Piece class has a few enum variables, nothing special. If I replace the function call with the following, all is good.

    if (threatener != null) System.exit(42);
    if (board[row][col] != null) {
        threatener = board[row][col];
        if (threatener == null) System.exit(41);
    }

What makes t point to null after it has successfully been assigned a non null object?


Solution

  • Java is always pass by value, reassigning an object reference inside a function doesn't effect it outside the function.

    Java is pass by value, the problem is that -with objects- the value that is passed is the reference...by value. This means if you pass an object (in Java, the objects address/reference is passed in) to a function then you can change the properties of an object (via it's reference) but you can't set the variable reference (which exists only inside the function) to another object because you are changing what the variable points to. The original reference that you passed in, remains the same because the function has lost its reference to it.

    If you return the object then you are returning the reference/address by value and setting it to a variable outside the function, so it works.