When a capacitor is charged by a battery, work is done by the charging battery at the expense of its chemical energy. This work is stored in the capacitor in the form of electrostatic potential energy.
Consider a capacitor of capacitance C. Initial charge on capacitor is zero. Initial potential difference between capacitor plates = zero. Let a charge Q be given to it in small steps. When charge is given to capacitor, the potential difference between its plates increases. Let at any instant when charge on
capacitor be q, the potential difference between its plates V = q/C
Now work done in giving an additional infinitesimal charge dq to capacitor
dW = Vdq =V = q/C dq
The total work done in giving charge from 0 to Q will be equal to the sum of all such infinitesimal works, which may be obtained by integration. Therefore total work

This work is stored as electrostatic potential energy of capacitor i.e.,
Electrostatic potential energy,

Energy density: Consider a parallel plate capacitor consisting of plates, each of area A, separated by a distance d. If space between the plates is filled with a medium of dielectric constant K, then
Capacitance of capacitor, C = Kε0A/d
If σ is the surface charge density of plates, then electric field strength between the plates

Charge on each plate of capacitor Q = σA = Kε0EA
∴Energy stored by capacitor,

But Ad = volume of space between capacitor plates
∴Energy stored,

Electrostatic Energy stored per unit volume,

This is expression for electrostatic energy density in medium of dielectric constant K.
In air or free space (K = 1), therefore energy density, ue = 1/2 ε0E2.