Immigrants have contributed billions of dollars more to Medicare in recent years than the program has paid out on their behalf, according to a new study, a pattern that goes against the notion that immigrants are a drain on federal health care spending.

The study, led by researchers at Harvard Medical School, measured immigrants’ contributions to the part of Medicare that pays for hospital care, a trust fund that accounts for nearly half of the federal program’s revenue. It found that immigrants generated surpluses totaling $115 billion from 2002 to 2009. In comparison, the American-born population incurred a deficit of $28 billion over the same period.

The findings shed light on what demographers have long known: Immigrants are crucial in balancing the age structure of American society, providing an infusion of young, working-age adults who support the country’s aging population and help cover the costs of Medicare and Social Security. And with the largest generation in the United States, the baby boomers, now starting to retire, the financial help from immigrants has never been more needed, experts said.

Individual immigrant contributions were roughly the same as those of American citizens, the study found, but immigrants as a group received less than they paid in, largely because they were younger on average than the American-born population and fewer of them were old enough to be eligible for benefits. The median age of Hispanics, whose foreign-born contingent is by far the largest immigrant group, is 27, according to the Brookings Institution. The median age of non-Hispanic whites in the United States is 42.