title: Extract first two characters of a String in Java
body: <p>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". </p>
  
  <p>If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". </p>
  
  <p>Note that <code>str.length()</code> returns the length of a string.</p>
  
  <pre><code>public String firstTwo(String str) {          
  
   if(str.length()&lt;2){
       return str;
   }
   else{
       return str.substring(0,2);
   }
  }
  </code></pre>
  
  <p>I'm wondering is there any other way can solve this question?</p>