I made a simple multi client chat application in Java (with the help of a book named HEAD FIRST JAVA). The application is working fine on localhost i.e when both client and server are run on same host and also working fine when I run server on one host and clients on other hosts in the same network. But the problem is I am not able to communicate with a friend of mine who is in some other network by using this application. Can anyone explain why ?
You already mentioned the problem: your friend is not in the same network as you.
I guess your application asks for the server's IP address on startup and then tries to connect to it. This is a valid approach and generally a good idea, as long as everything stays in the same network.
Now I'm guessing your friend is using a server IP address you provided him, that you looked up using some service like whatismyip.com. And that's the main problem here.
Assuming both of you are using a "normal" Internet connection for personal use, that IP you gave him is the one of your router. The router, however, does not know what to do with the chat client's request to connect to the server coming from your friend's computer. So it just drops the request.
The magic keyword in this case is "port forwarding" depending on the device, there should be a setting similar to this in your router's configuration screen. It allows you to forward all traffic arriving at a certain port to some host of your choice (which is, in your case, the server).
Be careful with these settings, as they allow access from the Internet to your local network!
Further, you will have to make the chat client try to connect on the port you configured your router to listen on. If it doesn't have an option for that yet, you will have to implement it and send your friend the updated application.