When a piece is not in the key of C Major or A Minor, it requires the use of accidentals. To avoid having to keep writing those accidentals, we can place them at the beginning of the piece using what is known as a key signature.
For instance, a piece in D Major's key makes regular use of the notes of F-sharp and C-sharp, so the key signature uses those accidentals. When this key signature is present, all F and C notes are automatically raised and become sharp notes unless the symbol of the natural accidental precedes them.
Following, we have a fragment from Beethoven's famous Ode to Joy, in D Major's key. Note how all the F and C notes are played sharp:
Practice key signatures construction and identification
For more information see:
Translated by Dan Román, revised by Sue Talley.