How to cancel order programmatically in magento 2?

In Magento 2 we can cancel an order using below way, Pass Magento/Sales/Api/OrderManagementInterface as DI to __construct() function. We can use Interface method to cancel the order in Magento 2.

Below code snippets is used for cancel order.

Call function like below from template or any PHP file, $orderId Must be an integer.

$orderId = 1;

The result will be getting based on order success like, You canceled the order successfully otherwise result will be like for error, You have not canceled the order.