






Early returns - jumping out of a method
Be careful not to jump out of the middle of a loop unless you found the thing you were looking for.
For example if you are looking for a string in a list of strings and if you find it you are supposed to
return the index of the thing you were looking for or else -1 to show that you didn't find it, don't do the
following:
public static int findString(List<String> wordList, String target)
{
int index = 0;
for (String word : wordList)
{
if (word.equals(target)
{
return index;
}
else return -1;
index++;
}
}
This should be
public static int findString(List<String> wordList, String target)
{
int index = 0;
for (String word : wordList)
{
if (word.equals(target)
{
return index;
}
index++;
}
return -1;
}
Link to this Page