Taken from: https://en.wikipedia.org/wiki/Electrostatics#Electrostatic_energy
A single test particle's potential energy, , can be calculated from a line integral of the work, . We integrate from a point at infinity, and assume a collection of particles of charge , are already situated at the points . This potential energy (in Joules) is:
where is the distance of each charge from the test charge , which situated at the point , and is the electric potential that would be at if the test charge were not present. If only two charges are present, the potential energy is . The total electric potential energy due a collection of N charges is calculating by assembling these particles one at a time:
where the following sum from, j = 1 to N, excludes i = j:
This electric potential, is what would be measured at if the charge were missing. This formula obviously excludes the (infinite) energy that would be required to assemble each point charge from a disperse cloud of charge. The sum over charges can be converted into an integral over charge density using the prescription :
This second expression for electrostatic energy uses the fact that the electric field is the negative gradient of the electric potential, as well as vector calculus identities in a way that resembles integration by parts. These two integrals for electric field energy seem to indicate two mutually exclusive formulas for electrostatic energy density, namely and ; they yield equal values for the total electrostatic energy only if both are integrated over all space.