Card 08/ 10

GotchaDifficulty: Intermediate1 min

Assigning to a Parameter Does Not Reach the Caller

The log shows the lower-cased email, and the saved record still has the capitals.

Java passes arguments by value: a method receives a copy of each argument, so assigning a new value to a parameter changes the method's own copy and nothing else, so a method cannot hand a result back that way. It has to return the result, and the caller has to use what comes back.

A method that is supposed to normalise a customer's email. It runs, the log inside it shows the lower-cased address, and the record saved afterwards still has the capitals in it:

java
static void normalise(String email) {
    email = email.toLowerCase();
    System.out.println("normalised: " + email);
}

String address = "[email protected]";
normalise(address);
System.out.println(address);
text

Line 2 assigned to email, which is the method's own parameter. The caller's variable address was never in reach: the method got a copy of what it held, and reassigning a copy changes nothing at the other end.

A method cannot hand something back by assigning to a parameter. It hands things back by returning them, so make the method return the normalised address and have the caller use what comes out.

java
static String normalise(String email) {
    return email.toLowerCase();
}

String address = normalise("[email protected]");