Very simply. They change their amount of internal air space, thereby changing their density.
You want to dive? You let water into your ballast tanks. You want to surface? You blow the water out with compressed air. It gets a bit tricky in reality, though, because the density of seawater actually varies a bit, depending on depth, temperature, and salinity (saltiness).
The density of the submarine, therefore, has to be continually adjusted.
Seawater is about 3 percent denser than fresh water. A ship in ocean water is therefore buoyed up by a 3 percent greater force than a ship in a lake, and it therefore floats a bit higher.
The Dead Sea and the Great Salt Lake are so dense from their high salt contents that their buoyancy is astonishing. Try floating in one of them if you ever get the chance. You’ll only sink in a few inches. It’s an amazing sensation.