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.

Related: 27 incredible photos of life on a US Navy submarine

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.

Brit Lab, YouTube

This video shows how American submarines dive and resurface using its ballast tanks:

Science Channel, YouTube