Card 08/ 10
All 10 cards
GotchaDifficulty: Intermediate1 min
Your Method Ran, Changed Something, and the Caller Saw Nothing
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.
static void normalise(String email) {
email = email.toLowerCase();
System.out.println("normalised: " + email);
}
String address = "Ada@Example.COM";
normalise(address);
System.out.println(address);normalised: ada@example.com
Ada@Example.COMLine 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.
static String normalise(String email) {
return email.toLowerCase();
}
String address = normalise("Ada@Example.COM");