here , i am creating file server program .in this i have noticed that socket s= null is written.i want to know actual reason why null is given.I thought that it is either related to the ObjectInputStream or Scanner.is it true it related to the ObjectInputStream or Scanner .Here the code for
Server.java
public class Server{
public static void main(String[] args){
Socket s=null;
ServerSocket ss=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
Scanner sc=new Scanner(System.in);
try
{
ss = new ServerSocket(1234);
System.out.println("server is created");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
try {
s=ss.accept();
System.out.println("connected");
oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject("Welcome");
ois= new ObjectInputStream(s.getInputStream());
}catch(Exception e)
{
e.printStackTrace();
}
try{
String fil=(String)ois.readObject();
FileInputStream fis = new FileInputStream(fil);
int d;
String data="";
while(true)
{
d=fis.read();
if(d==-1)
break;
data = data+(char)d;
}
oos.writeObject(data);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
can anyone explain actual reason? Thanks in advance .
The answer to your question is that it’s considered good practice to initialize variables to
nullif they are declared and assigned separately (rather than letting the compiler/execution environment initialize them for you. This goes back to early C where it was not guaranteed what value local variable was initialized to unless explicitly set.The Java compiler will generate an error if it detects that a variable is accessed without having been initialized or set. For example:
Will generate a compiler error on the last line, stating that the local variable may not have been initialized (since if the try-clause throws an exception before
sis assigned, it will never be set).In your case, this does not seem to be an issue since even if you are declaring your
Socketoutside of your try-block, you are never accessing it outside of the try-block scope.