This is accomplished by what's known as binding off, a simple and quick method for making a finished edge.
When you complete the last row of your pattern (or have knitted until you have at least enough yarn to make about three times the length of a row, if you're not using a pattern with a definite end) you will begin to cast off just as if you were continuing the pattern.
You'll often see patterns that say "bind off in pattern," meaning that you knit the knits and purl the purls just like you were doing in the body of the project.
Start by knitting or purling -- or whatever pattern stitch you were working in -- the first two stitches of the row.
Once you have two stitches on the right-hand needle, use the tip of the left-hand needle to pull the first stitch back up and over the second stitch and over the tip of the right-hand needle.
This will leave one stitch, actually the second stitch you worked, on the right-hand needle.
Knit or purl the next stitch as needed and repeat the process until you are left with no stitches on the left-hand needle and one stitch on the right-hand needle.
Some knitters like to go until they have two stitches on the left-hand needle, knit those two stitches together, then finish as usual. This makes for a bind off that looks a little more uniform across the top, rather than leaving a loose stitch hanging at the end.
Slip this last stitch off the needle. Trim your working yarn so that you have a few inches left over to weave into the finished work.
Slip this yarn through the loop and pull tight, securing the yarn so the loop won't unravel. You can also just pull the stitch until the tail end pulls through. This does not make a bump and looks a lot nicer in the finished work, but it's up to you.
Weave the end of the yarn through several stitches to secure the end, using either a sewing needle or a crochet hook.
Wear or use your new knitted item proudly!