Search code examples
javacompiler-errorsunreachable-code

Why this code got "unreachable statement" error?


I have the following method :

  char getChar(int I)
  {
    if (I<65+26) return (char)(I);

    switch (I)
    {
      case 91 : return '?';break;
      case 92 : return '#';break;
      default : return ' ';
    }
  }

Why does it get "unreachable statement" error ?


Solution

  • Because you can't break after you have already returned. return means "exit the method". break means "exit the block".

    So if you have:

    return '?'; break;
    

    then the break can never be reached.