Judge Hanen’s ruling was unexpected. In his ruling in 2015 about the program for parents, he made it clear that he thought both efforts to protect undocumented immigrants were illegal. Immigrant rights activists were bracing for a ruling by Judge Hanen against the DACA program.

In his ruling on Friday, Judge Hanen made it clear that he thought the DACA program was likely to be declared illegal in the long run. A spokesman for the Justice Department praised the judge for that part of his ruling.

“As the Justice Department has consistently argued, DACA is an unlawful attempt to circumvent Congress, and we are pleased the court agreed today,” said Devin O’Malley, the spokesman.

But the judge made a distinction between the two programs. He noted that the one aimed at parents, known as Deferred Action for Parents of Americans, had not yet been implemented when conservative attorneys general challenged its legality — a challenge that the judge agreed with.

He also wrote that, in his view, the legal problems with both programs “are basically identical.”

In the case of DACA, however, more than 700,000 young immigrants have come to rely on the program as a way of getting jobs and avoiding the prospect of being sent back to the country of their birth. The judge said that the potential harm to those immigrants was too great to simply end the program.

“The reality of the situation is that it conferred lawful presence and numerous other benefits, and many DACA recipients and others nationwide have relied upon it for the last six years,” Judge Hanen wrote.

He also added that “DACA is a popular program and one that Congress should consider saving.” Congressional action to come up with a permanent solution for the DACA program has stalled amid bitter recriminations between Mr. Trump and Democrats.