How to get domain URL using apex in Salesforce?

Use System.Url.getOrgDomainUrl() to get the Salesforce domain URL using Apex .  Use getOrgDomainUrl() in orgs with or without My Domain to retrieve canonical URLs. For example: https://yourDomain.my.salesforce.com, or, for orgs without My Domain enabled https://yourInstance.salesforce.com. Sample Code: Output: