I have a code with the following sequence of lines:
Socket echoSocket = null;
... something ...
echoSocket = new Socket("taranis", 7);
I do not understand why we want to have a first line. Well I know that Java is unable to define a type of the variable from its value. It’s why first we need to tell that echoSocket is variable which has Socket type (the first line) and than we tall that echoSocket has a certain value (an object of a class Socket).
But what I do not understand is why we need to assign a value two times? Why do we want to say that echoSocket is equal to null?
You do not need to assign a value to a local variable is it is not used. Code should generatlly not declare variables until necessary. There is a somewhat dull chapter in the JLS on definite assignment.
You problem seems to be with try-blocks. Resource handling should be written as:
In this case:
Catching of exception should go around the lot. Don’t try to save on try blocks.
If you find yourself repeating a lot of boilerplate, try the Execute Around Idiom.