This famous line, perhaps the most famous in Western literature, comes at the beginning of an extended soliloquy in which Hamlet is weighing the merits of life ("to be") against those of death ("not to be.") While this soliloquy has some suicidal overtones, and Hamlet is clearly very depressed at this point in the play, this soliloquy seems more of a forlorn philosophical musing than a statement of suicidal intent. In fact, later in the soliloquy he specifically says that not knowing what the hereafter will be like is enough to make one willing to live. Not only might one dream, which is "the rub," but things may be even worse in the afterlife than here on earth:
But that the dread of something after death
The undiscover'd country, from whose bourn
No traveller returns, puzzles the will,
And makes us rather bear those ills we have
Than fly to others that we know not of?
Before he sees Ophelia, which causes him to end his soliloquy, he seems to have come to the conclusion that, however miserable life is, it is better than "not to be," which is unknown and frightening.