Exception in thread main: java.lang.NullPointerException

Hello all,

I wrote a java program and I get a null pointer exception for this line:

for(int tmp=0;tmp<4;tmp++)

allservers[tmp].setindex(tmp);// Null pointer exception.

The line in main is this: (It calls a constructor which will be shown)

ServerMonitor shopservers = new ServerMonitor();

The allservers is synchronised within the following class:

This was within the constructor of the following class:

class ServerMonitor

{

boolean[] serverstates;

public Server[] allservers;

public ServerMonitor() // CONSTRUCTOR Here is the exception

{

serverstates = new boolean[4];

allservers = new Server[4];

for(int tmp=0;tmp<4;tmp++)

serverstates[tmp]=false;

for(int tmp=0;tmp<4;tmp++)

allservers[tmp].setindex(tmp);//NULL POINTER EXCEPTION

}

Also this is the class Server: (part of it)

class Server extends Thread

{

public int myindex;

public ServerMonitor monitor;

public StatusMonitor statmon;

public Server()

{

myindex=0;

}

public void setindex(int index)

{

myindex=index;

}

I would appreciate any help.

Thank you,

Nikos

[1276 byte] By [ngeoa] at [2007-10-3 2:50:53]
# 1

In this part of code:

serverstates = new boolean[4];

allservers = new Server[4];

for(int tmp=0;tmp<4;tmp++)

serverstates[tmp]=false;

for(int tmp=0;tmp<4;tmp++)

allservers[tmp].setindex(tmp); // NULL POINTER EXCEPTION

you create array of Server, but don't create array elements. After array creation all its elements are null, so you will have NullPointerException. You need change program in following way:

for(int tmp=0;tmp<4;tmp++)

{

allservers[tmp] = new Server();

allservers[tmp].setindex(tmp); // NULL POINTER EXCEPTION

}

S.B.a at 2007-7-14 20:39:44 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...