Q:

String out of bounds exception

Given a string, return true if the string starts with "hi" and false otherwise. Example output:
startHi("hi there") = true
startHi("hi") =true
startHi("hello hi") =false

Actual code:
   public boolean startHi(String str) {
  String firstTwo = str.substring(0,2);

if (str.length() < 2) return false;

  if (firstTwo.equals("hi")) {
  return true;
  } else {

  return false;
  }
}

Everything runs, except strings that are less than 2 characters. It keeps giving error of :
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:2) 

A:

You need to move the substring call behind the length check!
public boolean startHi(String str) {

  if (str.length() < 2) return false;

  String firstTwo = str.substring(0,2);
  if (firstTwo.equals("hi")) {
    return true;
  } else {
    return false;
  }
}

The call to substring fails otherwise, since it - as the exception tells us - requires a string of length 2 (or longer).
BUT
The entire method could be much less complex since Java strings have a startsWith method:
public boolean startHi(String str) {
  return str.startsWith("hi");
}

