Question:
Java Programming help..nullpointer exception.?
?
2011-05-24 10:56:39 UTC
My server syntax got a bit of error saying nullpointer exception. I dont know why and I can fix it. Hope you can help me since I need to submit my assignment tomorrow. Thank you.




import java.net.*;
import java.io.*;
import java.util.*;
import java.net.*;


public class GameServer {



public static void main(String args[]) {
ServerSocket serverSocket = null;
//ServerSocket receptionSocket = null;

System.out.println("Server started.. Waiting for clients.");

try {

serverSocket = new ServerSocket(1111);
}
catch (IOException ex) {
System.err.println("Cannot create server socket.");
}

for(;;)
{
Socket socke = null;

try {
socke = serverSocket.accept();//ERROR HERE
}
catch (IOException e) {
System.out.println("Problem accepting client socket.");
}

GameFrame calculator = new GameFrame(socke);

Thread t = new Thread(calculator);
t.start();

System.out.println("Calculator started.");

}
}
}
Three answers:
eli porter
2011-05-24 11:02:32 UTC
serverSocket.accept() is expecting an object, you are giving it a null reference.



first do:

Socket socke = new Socket() // not sure how to initialize but you get the idea



also you do not need to set objects to null.. ever. If you are coming from C\C++ you may be used to explicitly setting all declared variables as a safe programming practice (since C\C++ fills uninitialized variables with garbage data) but this is not necessary in Java.



In other words:

Socket socke = new Socket();



or even:

Socket socke;



is better than setting it to null at first.
Wolfman
2011-05-24 11:33:40 UTC
you shouldnt nullify the socket each loop turn this doesnt allow for correct socket close, remove the line

Socket socke=null;

and it should be fine
?
2016-11-19 07:10:07 UTC
NoClassDefFoundError skill that the no longer stumbled on classification grew to become into there once you compiled your source, yet is no longer on the classpath at runtime. you may desire to make useful that as quickly as you run your utility the "no longer stumbled on" classification is on the classpath. If its a substantial app, you may in all probability execute a command resembling: java -classpath /filesforapp:/jarsperhaps hi sturdy success! :^)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...