views:

376

answers:

3

I'd really appreciate some help with my program

    Exception in thread "Thread-4" java.lang.NullPointerException
    at ServerConnect.replyChoice(BaseStaInstance.java:63)
    at ServerConnect.run(BaseStaInstance.java:45)
    at java.lang.Thread.run(Thread.java:619)

my ServerConnect function looks like :-

class ServerConnect extends Thread {

 Socket skt;
 String sProcessId;
 ServerConnect scnt = null; 
 ObjectOutputStream myOutput;
 ObjectInputStream myInput;


 ServerConnect(){}
 ServerConnect(Socket connection, String sProcessNo) {
  this.skt = connection;
  this.sProcessId = sProcessNo;
 }

 public void run() {
  try {
   myInput = new ObjectInputStream(skt.getInputStream());
   ServerConnect scnt = new ServerConnect();

   while(true) {
    try{
     int ownTimeStamp = Global.iTimeStamp;

     Object buf = myInput.readObject();

     //if we got input, print it out and write a message back to the remote client...
     if(buf != null){
 LINE 45-->     **scnt.replyChoice(buf);**

     }

    }catch(ClassNotFoundException e) {
     e.printStackTrace();
    }
   }
  } catch(IOException e) {
   e.printStackTrace();
  }
 }

 void replyChoice(Object buf){


  try{
LINE 63 --> **myOutput = new ObjectOutputStream(skt.getOutputStream());**


  System.out.println("Server read:[ "+buf+" ]");
  myOutput.writeObject("got it");
  myOutput.flush();

  }catch(IOException e){
  e.printStackTrace();
  }
 }
}

Its basically a socket programming and multithreaded application. On executing it on different terminals inorder to have the client and server establish connections, I execute my code. But it throws up the error above on both terminals. Its just got something to do with my declaring the myOutput variable at the wrong place. Could someone help me out. From the error message, I've highlighted line 63 and line 45 in the piece of code attached.

+1  A: 

Your object is being initialised with the first constructor, which takes no parameters. As a result, skt is never initialised and is therefore null. When you call skt.getOutputStream(), it throws a null pointer exception because it cannot dereference skt.

Samir Talwar
thk u for ur help
rookie
A: 
 ServerConnect(){}
 ServerConnect(Socket connection, String sProcessNo) {
  this.skt = connection;
  this.sProcessId = sProcessNo;
 }

what constructor do you use ? cause skt might be uninitialised

//Edit : oh i see now you use the wrong constructor

   ServerConnect scnt = new ServerConnect();

to

   ServerConnect scnt = new ServerConnect(skt,sProcessId);
n00b32
thk u for ur help
rookie
+4  A: 
  1. Drop the default constructor
  2. Make your instance fields (stk and sProrcessId) final
  3. See how your compiler complains and fix those issues

These instructons help you trading runtime errors like your NPE to compile time errors, which is the best thing you can do. Note: This trick is meant to be used in general.

Willi
thk u for ur help
rookie