This a south/east/south-east asian thing, not specific to japanese. You will find the same in vietnam, korea, cambodia, thailand, taiwan, ...
I suspect that the cultural focus on cleanliness has a lot to do with it, but given that it's Hacker News there may be someone with a more exact idea of the origin.
Contrast with my experience in Sydney, where catching the bus during flu season is bloody hazardous. Being coughed and sneezed on gets old quickly, so I totally understand the surgical mask thing; it's a basic courtesy.