Well after Mario (Jumpman) defeated Donkey Kong, Peach was so grateful she stitched him a hat. Then Jumpman changed his name to Mario. Then the Valley Of Bowser heard of the hero and the princess, so...
Mario wears a hat because Mario's defense rapidly declines when he looses his hat. Which makes him vulnerable. He can't live without his hat. He needs it, it is his "security blanket.".
.
Also...