In Act I Scene 5, Hamlet sees the ghost of his father, who tells him of when and how and by whom he was murdered. When he receives this revelation, his close friends Horatio and Marcellus see the ghost but do not hear its revelation. Upon learning that his uncle murdered his father then married his mother, Hamlet is unsure what to do next. In this act, the ghost of his father demands that he swear to avenge his death and that his friends swear that they will never say anything about what they saw. In addition, Hamlet says:
There are more things in heaven and earth, Horatio,
Than are dreamt of in your philosophy. But come;
Here, as before, never, so help you mercy,
How strange or odd soe'er I bear myself,
As I perchance hereafter shall think meet
To put an antic disposition on,
That you, at such times seeing me, never shall,
With arms encumber'd thus, or this headshake,
Or by pronouncing of some doubtful phrase,
As 'Well, well, we know,' or 'We could, an if we would,'
Or 'If we list to speak,' or 'There be, an if they might,'
Or such ambiguous giving out, to note
That you know aught of me: this not to do,
So grace and mercy at your most need help you, Swear.
In other words, he already has the idea to behave like a madman. He does not say why, but we can surmise that his behaving like he's lost his marbles will provoke people to talk and perhaps fear less what he hears and repeats (because, once everyone believes he is mad, who would believe whatever strange stories he might utter?). This also buys him time to work out how he will determine the truth of the ghost's accusations (he tells these friends that it is an "honest ghost," but later puts his uncle to the test by having the players re-enact the murder the ghost told him of, suggesting that he still needs proof--as any man in his right mind would do before killing the king.
Another interesting question to consider as you read the play is whether Hamlet really is pretending to be mad--or is he truly mad? ;)