Caterpillar Cocoon and Chrysalis
Caterpillars are actually the larval form of moths and butterflies. They come in a variety of sizes and colors, depending on their species. Nearly all caterpillars are herbivorous and eat vegetation. They will create a cocoon (if they're a moth) or a chrysalis (if they're a butterfly) once they've consumed enough sustenance or reached a certain age. They can be hard, soft, and sometimes even translucent. Some caterpillars will decorate their cocoons with dirt or twigs to hide it from potential predators. A butterfly's chrysalis is not actually a cocoon, but is the hardened outer shell of the caterpillar itself. They will, however, use silk to attach themselves to trees.
Metamorphosis
Caterpillars undergo holometabolism, or complete metamorphosis, while in the cocoon or chrysalis. During this phase, the caterpillar undergoes a number abrupt, drastic physical changes. It develops wings, sprouts legs and loses many of the prickly hairs that initially covered its body. It also undergoes internal changes. The insects aren't resting while in their cocoons or chrysalises, and some can even move slightly or make noises to ward off predators. The caterpillar remains in this metamorphosis stage for nine to 14 days.
Emergence
The caterpillar emerges from its cocoon or chrysalis as a fully-fledged butterfly or moth once it has finished transforming. They use specialized mandibles to break out of their casings and usually have to pump liquid from their veins into their wings. They don't fly immediately, and instead rest on a vertical surface until their wings are straight and dry. The newly-formed adult's primary goal now is to mate and begin the process anew.
Other Insects
Moths and caterpillars aren't the only insects that build cocoons for the sake of metamorphosis. Many types of beetles, flies, ants, bees, fleas, mosquitoes and wasps also build cocoons. They don't all undergo complete metamorphosis like the caterpillar and butterfly; some go through partial metamorphosis, where they may go through slight physical changes each time they enter a cocoon to gradually transform into an adult.