The Russian economy contracted steeply in the second quarter as the country felt the brunt of the economic consequences of its war in Ukraine, in what experts believe to be the start of a yearslong downturn.

The economy shrank 4 percent from April through June compared with a year earlier, the Russian statistics agency said on Friday. It is the first quarterly gross domestic product report to fully capture the change in the economy since the invasion of Ukraine in February. It was a sharp reversal from the first quarter, when the economy grew 3.5 percent.

Western sanctions, which cut off Russia from about half of its $600 billion emergency stash of foreign currency and gold reserves, imposed steep restrictions on dealings with Russian banks and cut access to American technology, prompting hundreds of major Western corporations to pull out of the country.

But even as imports to Russia dried up and financial transactions were blocked, forcing the country to default on its foreign debt, the Russian economy proved more resilient than some economists had initially expected, and the fall in G.D.P. reported on Friday was not as severe as some had expected in part because the country’s coffers were flush with energy revenue as global prices rose.

Russia’s economic growth since annexation of Crimea

Year-over-year change in quarterly G.D.P.

Source: Russian Federal State Statistics Service

By The New York Times

Analysts, though, say the economic toll will grow heavier as Western nations increasingly turn away from Russian oil and gas, critical sources of export revenue.

“We thought it would be a deep dive this year and then even out,” Laura Solanko, a senior adviser at the Bank of Finland Institute for Economies in Transition, said of the Russian economy. Instead, there has been a milder economic decline, but it will continue into next year, putting the economy in a shallower recession for two years, she said.

Russia, a $1.5 trillion economy before the war started, moved quickly in the days after the invasion to mitigate the impact of sanctions. The central bank more than doubled the interest rate to 20 percent, severely restricted the flow of money out of the country, shut down stock trading on the Moscow Exchange and loosened regulations on banks so lending didn’t seize up. The government also increased social spending to support households and loans for businesses hurt by sanctions.