Let's start with the basics: Ships stay afloat because the weight of the water that it displaces equals the weight of the ship. As gravity pulls down on the ship; water creates an opposite upward force called buoyant force, which prevents the ship from sinking.
Submarines use ballast and trim tanks, which are filled with air or water to submerge or raise the ship. When the submarine is floating on the surface, the tanks are filled with air causing its density to be less than the surrounding water. When the submarine dives, the tanks are flooded with water causing its density to be greater than the water causing it to sink.
Some submarines use two hulls—one inside of another—instead of ballast tanks. This design allows it to flood the outer hull with water, which causes the vessel to sink, while the crew work and live in the inner one. An example of a double hull design is the Russian Alfa Class submarine considered by many to be the hot rod sub of the Cold War for its incredible speed. Designed during the 1960s, the Alfa Class submarine remains the fastest of its kind till this day, according to Foxtrot Alpha.
As the outer hull fills with water, the submarine dives.
As the water is replaced by air, the submarine resurfaces.
This video shows how American submarines dive and resurface using its ballast tanks: