Let's consider a rod of length \(L\) perpendicular to the axis of rotation through \(O\) as shown in Figure 2. Now we consider an infinitesimally small element of the rod of mass \(dm\) and thickness \(dx\) at a distance \(x\) from the axis of rotation.

Figure 2 A rod rotates about an axis perpendicular to the rod.

If the total mass of the rod is \(M\), the ratio of \(dm\) to the ratio of the total mass \(M\) is equal to the ratio of length \(dx\) to the total length \(L\). So you can write,

\[\begin{align*} \frac{{dm}}{M} &= \frac{{dx}}{L}\\ {\rm{or,}}\quad dm &= \frac{{M}}{L}dx \end{align*}\]

The moment of inertia of the element of the mass \(dm\) about the axis is

\[dI = dm{\kern 1pt} {\kern 1pt} {x^2}\]

The total moment of inertia of the whole rod is found by integrating the above expression from \(-l\) to \(L - l\) (see Figure 2).

\[\begin{align*} I &= \int\limits_{ - l}^{L - l} {dm\,{x^2}} = \frac{M}{L}\int\limits_{ - l}^{L - l} {\,{x^2}} dx\\ {\rm{or,}}\quad I &= \frac{1}{3}M({L^2} - 3Ll + 3{l^2}) \end{align*}\]

Case 1: When the axis of rotation passes through the left or right end that is, when \(l = 0\) or \(L = l\), the moment of inertia of the rod is \(I = \frac{1}{3}M{L^2}\).

Case 2: When the axis of rotation passes through the mid-point of the rod that is, when \(l = \frac{L}{2}\), the moment of inertia of the rod is \(I = \frac{1}{12}M{L^2}\).

You can also see here that the moment of inertia is different for different axis of rotation.