The capacitor is a charge storage device. Work has to be done to store the charges in a capacitor. This work done is stored as electrostatic potential energy in the capacitor.
Let q be the charge and V be the potential difference between the plates of the capacitor. If dq is the additional charge given to the plate, then work done is, dw = Vdq
dw = q/C dq (V = q/C)
Total work done to charge a capacitor is
w = ∫ dw = q∫0 q/C dq = ½ (q2/C)
This work done is stored as electrostatic potential energy (U) in the capacitor.
U = ½ (q2/C) = ½ CV2 (q = CV)
This energy is recovered if the capacitor is allowed to discharge.