Extract first two characters of a String in Java

Allen Li :

I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".

If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".

Note that str.length() returns the length of a string.

public String firstTwo(String str) {          

 if(str.length()<2){
     return str;
 }
 else{
     return str.substring(0,2);
 }
}

I'm wondering is there any other way can solve this question?

Andrew Jenkins :

Your code looks great! If you wanted to make it shorter you could use the ternary operator:

public String firstTwo(String str) {
    return str.length() < 2 ? str : str.substring(0, 2);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452371&siteId=1