The character of John Worthing changes his name to Ernest when he visits London. The reason he visits London is to get away from his daily life in the country, where he is the guardian of a young woman named Cecily. He also lives in a great country estate which belonged to Cecily's grandfather, Thomas Cardew. The latter had adopted John when he was a young boy and, upon his death, he made John take care of everything.
According to John Worthing, these are big responsibilities for which he needs to adopt a more serious and mature behavior despite being such a relatively young man.
When one is placed in the position of guardian, one has to adopt a very high moral tone on all subjects. It's one's duty to do so.
However, John/Ernest admits that such a serious position in no way reflects how he expects to conduct himself at all times. He admits that he has created an imaginary bad brother named Ernest, who supposedly lives in London, so that he can escape the country with the excuse that his brother did something that Jack has to go fix.
In reality, Jack goes to London to drink until late hours, to eat (a lot) at expensive restaurants, and to engage in whatever debauchery he feels like without responsibilities. After all, he is Algernon's friend for a reason. All this he does under the moniker of the invented brother, Ernest.
And as a high moral tone can hardly be said to conduce very much to either one's health or one's happiness, in order to get up to town I have always pretended to have a younger brother of the name of Ernest, who lives in the Albany, and gets into the most dreadful scrapes. That, my dear Algy, is the whole truth pure and simple.
In The Importance of Being Earnest the use of the homophones "earnest" and "ernest" is a play on words that reveals the central idea of the play: that it is important to be honest and tell the truth.
However, it is the irony of how things turn out in the play that produces the comedy. In the end John, whose father's name ends up being Ernest after all, would (by inheritance and by chance) turn out to be a "real" (earnest) Ernest.
However, throughout the entire play both John and Algernon live double lives, make up fake friends and, in John's case, change their names. That a lie turns out to be true begs the question of whether that would automatically make John an earnest man in the first place.