The U.S. Constitution provides that you are entitled representation by an attorney if the state is trying to deprive you of your liberty. This means that a court may be required to appoint a lawyer to represent you for free -- or for a fee you can afford -- if the crime you are charged with carries a jail sentence.
Because most criminal defendants are unable to afford their own attorneys, many states have public defender's offices. Public defenders (P.D.s) are fully licensed lawyers whose sole job is to represent poor defendants in criminal cases. Because they appear daily in the same courts, P.D.s gain a lot of experience in a short period of time. And because they work daily with the same cast of characters, they learn the personalities (and prejudices) of the judges, prosecutors, and local law enforcement officers -- important information to know when assessing a case and conducting a trial.
In areas that don't have a public defender's office, the local government will often contract with private law firms to take cases for indigent defendants. Or, the courts will maintain a list of attorneys and appoint them on a rotating basis to represent people who can't afford to hire their own lawyers.