At the end of the year, the teams are arranged in reverse order of their records. All the teams that didn't make the playoffs (ie. the bottom 7 in each conference) are put into a lottery, which is weighted in favour of the teams with the worst records. They determine which teams get the top three picks using the lottery, and then the rest of the teams are sorted in reverse record order. Once the lottery teams have been ordered, they then put in the playoff teams in reverse order after that.
It is possible to trade your pick in the draft to another team (if there's a player you want to get rid of, for example). In the scenario I'm interested in, New York has traded their first round pick to Houston. Now, if New York make the playoffs, then they cannot pick any higher than 15th. However, because of the imbalance between the conferences, they actually have the 9th worst record in the league, so if they were to miss out on the playoffs then they would be picking 9th (assuming they do not move up as a result of the lottery).
Because there are many fewer basketball players on the court at any time than in pretty much any other team sport, the value of a 'star player' is much higher than in other sports. It is possible for a single player to carry a team to a much greater extent than any other sport I've followed. A consequence of this is that it is VERY valuable to have a high pick in the draft - if you can find the potential star, he will significantly improve your team's performance. For example, this year there is one player (Anthony Davis) that scouts are saying will be a superstar some day - if you can draft him onto your team, then you're set for years to come (at least in theory...projections of superstardom don't always come true).
Unfortunately, that leads to some teams pursuing a 'tanking' strategy - they will trade their good, older players for as many draft picks as they can with the aim of doing very badly, get high picks in the draft for a couple of years and in theory end up with a nucleus of very talented youngsters who as they mature will lead the team to glory. The idea behind the lottery system is to prevent this from happening - you are not guaranteed the top pick if you do badly. But unfortunately it doesn't do enough to stop teams from bottoming out - there are at least two teams this year (New Orleans and Charlotte) who are transparently employing this strategy. They will still be getting a very high draft pick, even if it's not necessarily the #1 pick.