Question 1
Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".
helloName("Bob") → "Hello Bob!"
helloName("Alice") → "Hello Alice!"
helloName("X") → "Hello X!"
public String helloName(String name) {
}Main Solution
The method should concatenate the string "Hello ", the parameter name, and the exclamation mark "!", then return the result.
public String helloName(String name) {
return "Hello " + name + "!";
}
Explanation:
- The method receives a
Stringparameter calledname. - Using the
+string concatenation operator, we build the greeting:"Hello "+name+"!". - For example, if
nameis"Bob", the expression evaluates to"Hello Bob!". - The resulting string is returned with the
returnstatement.
Teacher Explanation
"Hello " + name + "!", combining a string literal, the parameter, and another string literal.Education Coach Advice
+ operator concatenates strings. Always double-check that your spacing and punctuation (like the space after "Hello" and the "!" at the end) exactly match the required output format.Traps
"Hello" + name + "!" instead of "Hello " + name + "!", which would produce "HelloBob!" instead of "Hello Bob!". Another trap is omitting the exclamation mark at the end.
