Generally, the police can demand identification under two circumstances: if you are suspected of a traffic offense, or if you are in a state with loitering laws and you are violating them.
If you are driving and are stopped by the police for a traffic violation, they have the right to demand identification.
In those states with loitering laws, the police can demand identification of a person loitering, usually defined (at least according to Nolo.com, a legal publisher's website) as "wandering about from place to place without apparent business, such that the person poses a threat to public safety."
That's the short, layperson's answer. An analysis of this issue by someone with legal training is provided at