It essentially generates a code based on a pre-shared secret and the current time.
As for the costs, as I said there's plenty of free client applications (Google Authenticator is just the most well known), and not only there are plenty of libraries that you can use on your server, as the RFC that details TOTP provides an implementation in less than 50 short lines of code (+ Java boilerplate); see http://tools.ietf.org/html/rfc6238
And you just need that, plus an extra field in your data store for each user (to store the secret) and a textbox in the login page.