'Return string of first character if it contains more than 4 characters, otherwise return the last character

The question is: Given a string return the first character in the string if it contains more than 4 characters, and the last character otherwise. Example out comes below

firstOrLastChar("kwk") -> 'k'
firstOrLastChar("gals") -> 's'
firstOrLastChar("uocrws") -> 'u'

This is the code I've gotten done, but it returns a char not a string so i get this type of error of it being incompatible types. really lost on how to go about it

  if (str.length() > 4)
        return str.charAt(0);
    return str.charAt(str.length() - 1);


Solution 1:[1]

If I understand your question, it looks like you want to return a String type instead of char type, then you can do following :

if (str.length() > 4)
        return String.valueOf(str.charAt(0));
    return String.valueOf(str.charAt(str.length() - 1));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashish Patil