The continuity equation is developed for the stellar mass content of galaxies, and exploited to derive the stellar mass function of active and quiescent galaxies over the redshift range $zsim 0-8$. The continuity equation requires two specific inputs gauged on observations: (i) the star formation rate functions determined on the basis of the latest UV+far-IR/sub-mm/radio measurements; (ii) average star-formation histories for individual galaxies, with different prescriptions for discs and spheroids. The continuity equation also includes a source term taking into account (dry) mergers, based on recent numerical simulations and consistent with observations. The stellar mass function derived from the continuity equation is coupled with the halo mass function and with the SFR functions to derive the star formation efficiency and the main sequence of star-forming galaxies via the abundance matching technique. A remarkable agreement of the resulting stellar mass function for active and quiescent galaxies, of the galaxy main sequence and of the star-formation efficiency with current observations is found; the comparison with data also allows to robustly constrain the characteristic timescales for star formation and quiescence of massive galaxies, the star formation history of their progenitors, and the amount of stellar mass added by in-situ star formation vs. that contributed by external merger events. The continuity equation is shown to yield quantitative outcomes that must be complied by detailed physical models, that can provide a basis to improve the (sub-grid) physical recipes implemented in theoretical approaches and numerical simulations, and that can offer a benchmark for forecasts on future observations with multi-band coverage, as it will become routinely achievable in the era of JWST.