A handgun was found in the backpack of a 7-year-old student at a public elementary school in Queens on Thursday morning, New York City officials said, leading to a tense few hours as the school was placed on lockdown while the police made sure there was no danger.

It remained unclear how the gun, a .22-caliber semiautomatic pistol, ended up in the boy’s backpack. The police said that a magazine, separated from the pistol but loaded with 10 bullets, and a plastic bag with 7 to 10 additional rounds of ammunition were also found in the boy’s bag. Officials had yet to determine whether there was a bullet in the gun’s chamber, Paul J. Browne, the Police Department’s chief spokesman, said on Thursday, but the weapon was not fired.

“The question of whether the child saw” the gun and ammunition “and put it in his backpack, or an older brother hid it there, is still under investigation,” Mr. Browne said.

The boy, a second grader, arrived at Wave Preparatory Elementary School in Far Rockaway about 7:30 a.m. About two hours later, the boy’s mother learned that he had the gun and she raced to the school. She told administrators that she needed to take him out of school for a dentist appointment, Mr. Browne said.