ytd2
is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.
Alternatively, you can also call an external process like youtube-dl
to do the job. This is probably the easiest solution but it isn't in "pure" Java.