Encoder and example code help

Can someone give me just a brief explanation of an encoder and how it works and also some example code using moters or servos.