Police say Abraham Sosa walked into the subway tunnel to go to the bathroom past a no trespassing sign in the Kingsbridge station Monday afternoon.
Officers followed and when they asked for his ID he refused to show it and resisted an attempt to arrest him.
During the struggle, the machine gun fell out of his backpack.
Sosa is facing charges including assault and criminal possession of a weapon.
He told police he had to carry it around with him because his mother didn't want it in the apartment.
25 bullets were also recovered, police said.
Two officers suffered minor injuries.
A 21-year-old man is also charged for interfering with Sosa's arrest and stealing an officer's phone.
* Get Eyewitness News Delivered
* Follow us on YouTube
* More local news
* Send us a news tip
* Download the abc7NY app for breaking news alerts