HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java FizzString

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fizzstringjavastackoverflow

Problem

I am testing what knowledge I have with the FizzBuzz tests in Java. This is the one I just completed:


Given a string str, if the string starts with "f" return "Fizz". If the string ends with "b" return "Buzz". If both the "f" and "b" conditions are true, return "FizzBuzz". In all other cases, return the string unchanged.

My code (working):

public String fizzString(String str){

    if (str.startsWith("f") && str.endsWith("b")) {
        return "FizzBuzz";
    }

    if (!str.startsWith("f")) {
        if (!str.endsWith("b")) {
            return str;
        } else return "Buzz";
    } else return "Fizz";
}


Questions: How can I make this code more efficient? Should I be assigning "Fizz" and "Buzz" to separate string variables, so that there is just one return statement at the end of the method? Should there be fewer if statements - if so, I'm not sure how it would be done. How would you go about the problem?

Solution

Here is a very direct translation of the problem into code.

public String fizzString(String str) {
    if (str.startsWith("f") && str.endsWith("b")) {
        return "FizzBuzz";
    } else if (str.startsWith("f")) {
        return "Fizz";
    } else if (str.startsWith("b")) {
        return "Buzz";
    } else {
        return str;
    }
}


Compared to your original code, it is easier to read because:

  • There is no nesting



  • All conditions are affirmative, not a mixture of affirmative and negative



There is no advantage to assigning the result to a variable and returning that variable.

If you want a single return statement, you can write:

public String fizzString(String str) {
    return str.startsWith("f") && str.endsWith("b") ? "FizzBuzz"
         : str.startsWith("f")                      ? "Fizz"
         :                        str.endsWith("b") ? "Buzz"
                                                    : str;
}


… which likely compiles to exactly the same code. Choose whichever version you think is more readable.

Code Snippets

public String fizzString(String str) {
    if (str.startsWith("f") && str.endsWith("b")) {
        return "FizzBuzz";
    } else if (str.startsWith("f")) {
        return "Fizz";
    } else if (str.startsWith("b")) {
        return "Buzz";
    } else {
        return str;
    }
}
public String fizzString(String str) {
    return str.startsWith("f") && str.endsWith("b") ? "FizzBuzz"
         : str.startsWith("f")                      ? "Fizz"
         :                        str.endsWith("b") ? "Buzz"
                                                    : str;
}

Context

StackExchange Code Review Q#85580, answer score: 5

Revisions (0)

No revisions yet.