Coffee Addict Coffee Addict - 7 months ago 9
Java Question

Returning a substring's content vs. returning the substring itself

I was wondering if this;

public String seeColor(String str)
{
int l = str.length();
if(l >= 3 && str.substring(0, 3).equals("red")) return "red";
if(l >= 4 && str.substring(0, 4).equals("blue")) return "blue";
else return "";
}


was faster to compile then this;

public String seeColor(String str)
{
int l = str.length();
if(l >= 3 && str.substring(0, 4).equals("red")) return str.substring(0, 4);
if(l >= 4 && str.substring(0, 5).equals("blue")) return str.substring(0, 5);
else return "";
}


or maybe both ways suck and there's another, more efficient approach that I am not aware of?

Answer

Each call to substring does work to get the generate the substring, so the first choice is more efficient. However, your current code isn't null safe (so I would test for null) and I would prefer String.startsWith(String) like

public String seeColor(String str)
{
    if(str == null) return "";
    else if(str.startsWith("red")) return "red";
    else if(str.startsWith("blue")) return "blue";
    else return "";
}