If a magnetic field is sustained, there must be a current in a closed circuit or loop, implying some energy has been spent in creating the field. If this energy is not dissipated via the circuit's resistance, it is stored in the field.
Take an ideal inductor with zero resistance. Although it's practically impossible, assume that the coil's resistance is so small that it is practically negligible. The loss of the field's energy to dissipate thermal energy (or heat) is thus negligible.
The energy stored can be easily calculated by writing down the EMF generated across it as it resists the change of current through it in the presence of a variable current source. The power is given by the product of the induced EMF and the current at any instant, and integrating it over time gives the energy stored.
The magnetic energy density is given by the energy per unit volume, which can be easily derived from the geometry of the coil.
We find remarkable similarities between the magnetic energy with the electrical energy stored in a capacitor and the corresponding electrical and magnetic field energy densities.
If, instead of a vacuum, there is a material with magnetic permeability different from that of a vacuum, then the corresponding magnetic permeability replaces the magnetic permeability of a vacuum in the expression derived, just like the case of electric field energy density in a capacitor.
Although the expressions derived are for special inductors, they can be shown to hold in general.
Magnetic field energy has important practical applications in generating electrical sparks in gasoline-powered automobile engines. The fuel-air mixture in the engine needs to be ignited with a spark, which is supplied by a system of coils in the engine. The system consists of primary and secondary coils, with more turns on the secondary coil than the primary coils. The primary coils are connected to the car’s battery and generate a strong magnetic field, thus storing energy in the field.
During ignition, the current in the primary coils is interrupted. Thus, the magnetic field and the magnetic field energy density in the primary coils reduce to zero rapidly. The secondary coils, which surround the primary coils, are thus subjected to a high electromotive force of tens of thousands of volts, which creates a high pulse through the secondary coils and, ultimately, to the connected spark plugs.