Same as the swim bladder in many species of fish.
Whether you float or sink depends totally on your density relative to the water - i.e. the amount of volume to take up, and the mass they contain.
The volume of a submarine is fixed, but the amount of mass they contain depends on the amount of water they contain (same as with a ship, if you punch a hole in the ship, water comes into the ship, which then increases the mass of the ship, and generally this can cause the ship to sink). The difference between a surface ship and submarine is that a surface ship generally tries to keep the water out in order to stay buoyant, while a submarine has ballast tanks that are designed to be flooded when required to sink, and to have the water pushed out of it when the submarine wishes to rise towards the surface.