When you were a kid, all you probably understood about cavities is that if you didn't brush and floss, you had a good chance of getting them. You also knew that it would lead to a dentist giving you something called a filling.
To understand how a cavity forms, you need to have an understanding of your teeth. Each tooth is covered by a hard mineral substance called enamel. The enamel helps to protect your teeth, but because it's a mineral, it can break down when it makes contact with the acids in your mouth. This is one of many reasons why drinking water is really good for the health of your mouth. It washes over your teeth and gums along with your saliva, helping to combat the acid and buildup of bacteria. Sugars and starches are the main enemies here, because bacteria thrive on them.
Once enough bacteria builds up, it's going to form into plaque and then tartar, two or more enemies of your enamel. If you fail to take care of your teeth by brushing, flossing and drinking plenty of water, then the tartar and plaque will eventually eat away at the enamel, forming tiny holes that compromise the hard surface. This is what's known as tooth decay. If enough acid builds up over time, these tiny holes get a little larger until they eventually become cavities.
Brushing with fluoride toothpaste twice daily, flossing once per day, drinking lots of water and rinsing with an alcohol-free mouthwash are all excellent preventative measures. You can also avoid sugary or starchy foods and, of course, visit your dentist twice a year for regular, professional cleanings.