The visit, video of which was shared on Mr Obama's Instagram account, was part of "supporting the next generation of leaders", a spokesman said.
“Hey, how’s it going everybody?” Mr Obama said, as he strode into the room.
“The chancellor told me you guys were meeting, so I thought I’d stop by. You don’t mind me crashing, right?”
As pupils reacted in an apparent state of disbelief at the surprise visitor, the former leader added: “One of the things that I did throughout my presidency was I’d meet with groups of young people everywhere I went, whether it was here in the United States, or travelling overseas just to kind of hear from them, find out what they’re interested in.
“I do believe that most of the problems that we have are going to be solved by you.”
Before he left the building he told one girl: "Remember what I say: don't back down".
As he departed, students could be heard screaming in excitement.
You do not have access to view this Atom.
Mr Obama's spokesman Keith Schiller said in a statement the former president attended the school for a discussion with students about “their life goals, pursuing higher education and giving back to their communities.”
“President Obama is focused on supporting the next generation of leaders," he said. “Today’s meeting is part of that ongoing conversation with young people.”
The former president recently condemned Donald Trump's decision to axe the Deferred Action for Childhood Arrivals (Daca) immigration policy – one of Mr Obama's signature manoeuvres – calling the decision “cruel, self-defeating and wrong”.
Mr Obama had personally appealed to Mr Trump to keep the programme, which prevented nearly 800,000 people who came to the US as children from being deported.
“Whatever concerns or complaints Americans may have about immigration in general, we shouldn’t threaten the future of this group of young people who are here through no fault of their own, who pose no threat, who are not taking away anything from the rest of us,” Mr Obama said.
Mr Obama will reportedly be hosting his first fundraising event for the Democratic National Committee later in September in Washington. The money raised will go towards state parties and upcoming elections in Virginia.
More about: #Obama