I would like prevent anyone trying to access my website thro' code. Code in the sense, any program that is like bot, which would cause traffic surge.
For instance,
URL url = new URL("http://www.example.com");
URLConnection yc = url.openConnection();
I would like to prevent the above java code from opening a connection.
Is this possible and if I can do so, will that cause any side effects(User unable to access the website through specific browser)?
Short answer is you can't. However, you can make some checks like user agent (but again, this is easily changed/spoofed).
But let's say you want to get the majority, check that the User Agent is acceptable, check the device for mobile devices accessing you page.
Another method I know that people have done is track the number of requests a source is making and having a threshold of request / time to test if the connection is "legit". I haven't done this myself, so I can't speak to it's reliability.
If you want to distinguish between robots, tools like ( ReCaptcha) will help.