to protect yourself from other people's cold
Yes, as all the other sempais say, the masks are for protecting yourself from pollen, and to protect others from your your virus and cold.
I think it is also a way to protect yourself from other people's virus and cold, when you feel weak. No Japanese people would admit this of course but it is true.
There are many types of masks, all with fancy and ergonomic shapes, sometimes in color, or with Hello Kitty. There is even the type of mask that avoids your glasses to get foggy!
It remains a mystery though why the Japanese people do not feel it odd to wear masks. I certainly would. Even though I have been living such a long time here, I cannot convince myself to wear a mask. However, and this is Japan or you, I feel a bit disgusted if someone coughs without wearing a mask.
Japan is such a peaceful place that it is possible to wear a surgical mask (and glasses and a hat) and not be arrested, either by the police as a might-be-terrorist or to get an autograph by a Michael Jackson fan!