Algernon Moncrieff lives in the city and is a social dandy with luxuriant tastes and leisurely manners. He is also not very fond of social occasions with family and boring guests. Pampered and overly indulgent of his every whim, Algernon has invented a friend called Bunbury who lives in the country. Mr. Bunbury is conveniently chronically ill and Algernon is a conveniently dedicated, loyal friend. Therefore, at Bunbury's every shift of ill health, Algernon drops everything--especially dinners with his aunt, Lady Augusta Bracknell, and cousin, Gwendolen Fairfax (and, yes, Lady Bracknell is Gwendolen Fairfax's mother)--and runs to Bunbury's side to nurse him through his illness. As a result, Algernon goes "Bunburying" at a whim and loves his escapes from the city to the country.
On the other hand, Jack, properly called John Worthing, has a house in the country where he is the guardian of his benefactor's granddaughter, Cecily Cardew. Jack was a foundling--he was found in a handbag in a cloakroom at the railway station, London's Victoria Station, to be precise. No one knew his parentage and since it was Thomas Cardew who discovered the baby in the handbag that was Jack, Cardew raised him as his guardian. Jack dislikes living in the country and whenever he can, he escapes the country to go to the city courtesy of his imaginary brother Earnest who is a rascal and a ne'er-do-well who is constantly getting into trouble and requiring rescuing.
While Algernon and Jack, unbeknownst to themselves, have similar made-up escapes from tedium, their escapes are in reverse order. And while Algernon is careless in the city, he pretends to be serious and in earnest in the country; so when he assumes the identity of Jack's imaginary brother Earnest, the name is strangely suited to him. Jack similarly is above reproach in the country and has to escape to be a rascal and social dandy (like Algernon) named Earnest in the city. Their routes are, as was said, opposite although both behave in the country and misbehave in the city.