Bears don't attack for no reason. They generally attack because they're hungry and either think you're a source of food or are a threat - usually to their cubs. Polar bears have been known to eat people. You're a fool if you go anywhere near them unarmed. It is much rarer in grizzlies and brown bears.
However bears are unpredictable, which is what makes them dangerous. Sometimes black bears are almost comically startled by people, and run at the first sight. Sometimes they are completely unfazed. There are even stories of black bears stalking people. Some people say you should make noise while hiking to let bears know you're coming so you don't startle them - others say you should not announce your presence more than necessary.