helloName Solution

For this CodingBat problem you were given a string name and tasked to return a string with the form "Hello name!", so if name was Bob your method should return "Hello Bob!".

Examples

helloName("Bob") => "Hello Bob!"
helloName("Alice") => "Hello Alice!"
helloName("X") => "Hello X!"

Starter Code

public String helloName(String name) {

}

Solution

public String helloName(String name) {
    return "Hello " + name + "!";
}

This is the shortest solution, concatenating the string "Hello " with the string name and the string "!" on a single line.

But, you can also create an intermediate local variable to hold the concatenation and return that.

public String helloName(String name) {
    String st = "Hello " + name + "!";
    return st;
}

Functionally the two are the same. They both return the same string, and are both correct. I do find that, especially earlier in the year, students find the second solution more clear because it separates out the two tasks.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.