ISLAMABAD, Pakistan — Sri Lanka plunged into a constitutional crisis Friday after the president ousted the prime minister, a move that took the nation by surprise and was denounced as illegal by some government ministers.

Sri Lankans were glued to their television sets Friday after President Maithripala Sirisena dismissed Prime Minister Ranil Wickremesinghe and replaced him with Mahinda Rajapaksa, a popular former leader who was accused of human rights abuses, brazen nepotism and excessively close ties to China when he governed the country.

The swearing-in ceremony, broadcast live, was a moment of high political drama for Sri Lanka, with Mr. Rajapaksa grinning as he shook Mr. Sirisena’s hand. The men were former political allies until the president broke away from Mr. Rajapaksa’s party to unseat him in 2015.

Fireworks and celebrations broke out across Sri Lanka after the swearing in ceremony, but the capital, Colombo, was uneasy as some cabinet ministers declared the move unconstitutional. Mr. Rajapaksa was sworn in at about 7 p.m. as representatives of the navy, air force and army watched in a stately room inside the presidential secretariat.