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.

<?php

public function __construct(
    \Magento\Sales\Api\OrderManagementInterface $orderManagement
) {
    $this->orderManagement = $orderManagement;
}
/**
 * int $orderId
 * Order cancel by order id $orderId 
 */
public function cancelOrder($orderId) {
    try {
        $this->orderManagement->cancel($orderId);
        return __('You canceled the order successfully.');
    } catch (\Exception $e) {
        return __('You have not canceled the order.');
    }
}

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

$orderId = 1;
$this->cacelOrder($orderId);

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.