Solution (source code)

= Solution

The <Hamiltonian density> is $\mathcal H=[\dot\phi^2+(\partial_x\phi)^2+m^2\phi^2]/2$. In the vacuum only $\langle a_na_m^\dagger\rangle=\delta_{nm}$ contributes. Hence
$$
\langle\dot\phi^2\rangle=\sum_n\frac{\omega_n}{L}\sin^2(k_nx),\quad
\langle(\partial_x\phi)^2\rangle=\sum_n\frac{k_n^2}{\omega_nL}\cos^2(k_nx),\quad
\langle\phi^2\rangle=\sum_n\frac{\sin^2(k_nx)}{\omega_nL}.
$$
Substitution, using $\omega_n^2=k_n^2+m^2$, yields
$$
\boxed{\langle\mathcal H(x)\rangle
=\sum_{n=1}^\infty\left[\frac{\omega_n}{2L}-\frac{m^2}{2\omega_nL}\cos(2k_nx)\right].}
$$
This <Dirichlet scalar vacuum energy density> illustrates why a massive field's local unregularized energy density need not be uniform. The cosine integrates to zero over the interval, so
$$
\boxed{E_0^{\rm BC}(L)=\int_0^Ldx\,\langle\mathcal H(x)\rangle
=\frac12\sum_{n=1}^\infty\omega_n.}
$$
These divergent expressions are understood with a common regulator before exchanging sums, integrals or derivatives. <Normal ordering> the <Hamiltonian operator> separately in each geometry would erase the vacuum terms one is trying to compare; a common regulated subtraction is used instead in <7/c> and <7/d>.