How can I replace this "if" expression with something else?

a beginner coder here. So I have this block of code:

public String doOperation(String s1, String s2) {
    if(s2.compareTo("") == 0) return s1;
    else return s2;
}

      

Just a rough draft, but essentially what I'm saying is to return s2 if it's not an empty string, then return s1. Is there a way to do this without an if statement? For assignment, I shouldn't use if, switch, while, loop, exception handling, or almost anything else, which is just a hidden way to get around the if statement.

I'm trying to find a way to do this through polymorphism, but I also don't want to create a ton of new things to get this tiny task done. Any ideas / help? Thank!

+3


source to share


6 answers


You can use the ternary operator:



return s2.isEmpty() ? s1 : s2;

      

+3


source


Sounds like a bit of a brain teaser .. It's terrible code, but it should do what you want ...

return s1.substring(Math.min(s1.length()-1, s1.length() * s2.length()) + s2

So if the length of s2 is 0, you would print s1 starting at position 0 followed by s2 which is empty



If s2's length is not 0, you will print s1 starting at the last position (i.e. nothing) followed by s2

Oh boy, now I feel dirty :)

+2


source


He called Triple Operation Super Helpful

public String doOperation(String s1, String s2) {
    return s2.compareTo("") == 0 ? s1 : s2;
}

      

+1


source


Since everyone else covered ternary (or conditional operator ? :

), you could also do it with switch

like

public String doOperation(String s1, String s2) {
    switch (s2.length()) {
    case 0: return s1;
    }
    return s2;
}

      

+1


source


You should always make sure to do null scripting and exception handling first.

public String doOperation(String s1, String s2) {
    if (s2 == null) {
        System.out.println("Error Msg: null value");
        throw new NullPointerException();
    }
    return s2.isEmpty() ? s1 : s2;
}

      

Update 1: For this particular scenario, using s2.isEmpty()

is slightly faster or has a better coding style compared to s2.equals("")

either s2.length() == 0

ors2.compareTo("") == 0

+1


source


public String doOperation(String s1, String s2) {
    int mask = 1 / (1 + s2.length());
    return s1.substring(0, s1.length() * mask) + s2);
}

      

The mask will be 0

for any non String

- empty due to integer

-arithmetic and 1

for empty String

, like 1 / 1 = 1

.

In the second line, the mask 0

"nullifies" the length of the substring, leaving it empty, and the added one s2

is the only thing that is returned.

On the other hand, the mask 1

will not change the value s1.length()

, and the added one is s2

empty anyway (since we got the mask 1

), so it only returns s1

from start to end.

+1


source







All Articles