java.lang.nullpointer exception

Hi, this is my code., it gives , nullpointer exception .... please correct it.
It is basically implementation of bully algorithm., there you have to open 5 console windows and execute code Election 0, Election 1, Election 2, Election 3, Election 4. In everywindow that exception occurs as a result of which the array list in the code does not contain the port numbers of other processes running. Please correct it.

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


public class Election
{
      String c1 = new String("ELECTION");
      String c2 = new String("OK");
      String c3 = new String("DENY");
      String c4 = new String("COORDINATOR");
      DatagramSocket d;
      InetAddress inet;
      static int count_ok;
      static int count_nook;
      static int elect = 0;
      static boolean flag = true;
      static boolean head = false;
      Client c;
      ArrayList array_port = new ArrayList(5);
      reader readMember;
      String answer = "";

      public static void main(String args[])
      {
            int value = Integer.parseInt(args[0]);
            Election e = new Election(value);
      }

      public Election(int value)
      {
            int port;
            for(int j=0;j<5;j++)
            {
                  array_port.add(j,new Integer(j));
            }
            Server s = new Server(value);
            port = s.getPort();
            readMember = new reader(port,value);
            s.start();
            readMember.start();
            c = new Client(value,port);
            c.start();

      }


      class reader extends Thread
      {

            int port,value;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            byte[] by;
            DatagramPacket dp1;
            DatagramSocket ds;


            public reader(int p,int val)
            {
                  port = p;
                  value = val;
            }

            public void run()
            {
                  try {
                  System.out.println("Enter start anytime if u want to elect and exit if u want to exit");
                  while(flag == true)
                  {
                        answer = bufferedReader.readLine();
                        if(answer.equals("start"))
                        {
                              execute();

                        }
                        else if(answer.equals("exit"))
                        {
                              flag = false;
                              by = ("DOWN"+":"+(new Integer(value)).toString()).getBytes();
                              for(int i=2000;i<2005;i++)
                              {
                                    if(i!=port)
                                    {
                                          dp1 = new DatagramPacket(by,by.length,inet,i);
                                          d.send(dp1);
                                    }
                              }
                              head = false;
                              d.close();
                        }
                  }
                  }catch(Exception e) {System.out.println("In reader class\n");System.out.println(e);}

            }


            public void execute()
            {
                  int j;
                  count_ok = 0;
                  count_nook = 0;
                  elect = 1;
                  try {
                  for(int i=2000;i<2005;i++)
                  {
                        j = ((Integer)array_port.get(i-2000)).intValue();
                        if(i!=port)
                        {
                              if(j == i)
                              {
                                    by = (c1 + ":"+ ((new Integer(value)).toString()) ).getBytes();
                                    dp1 = new DatagramPacket(by,by.length,inet,i);
                                    System.out.println("Sent "+c1+" to Member "+(i-2000)+" on port "+i);
                                    d.send(dp1);
                              }
                              else
                              {
                                    count_ok++;
                              }
                        }
                  }

                  }catch(Exception e) {System.out.println("In Execute method\n");System.out.println(e); }
                  if(count_ok == 4)
                  {
                        System.out.println("I AM COORDINATOR SINCE ALL OTHER PROCESSES ARE DOWN");
                        count_ok = 0;
                        head = true;
                  }
            }


      }


      class Server extends Thread
      {
            int p;
            int val;
            DatagramPacket dp2;
            byte[] by;

            public int getPort()
            {
                  return p;
            }

            public Server(int v)
            {
                  val = v;

                  if(v == 0)  p = 2000;
                  if(v == 1)  p = 2001;
                  if(v == 2)  p = 2002;
                  if(v == 3)  p = 2003;
                  if(v == 4)  p = 2004;
            }

            public void run()
            {
                  try
                  {
                        d = new DatagramSocket(p);
                        array_port.set(p-2000,new Integer(p));
                        System.out.println("Running on Port "+p);
                        inet =      InetAddress.getLocalHost();
                        by = ("UP"+":"+(new Integer(val)).toString()).getBytes();
                        for(int i=2000;i<2005;i++)
                        {
                              if(i!=p)
                              {
                                    dp2 = new DatagramPacket(by,by.length,inet,i);
                                    d.send(dp2);
                              }
                        }
                  }
                  catch(Exception e) {
                        System.out.println("In run method of Server class\n");
                        System.out.println(e);
                        }

            }
      }



      class Client extends Thread
      {
            int val;
            int port;

            public Client(int v,int p)
            {
                  val = v;
                  port = p;
            }

            public void run()
            {
                  DatagramPacket dp,dp1;
                  byte[] by = new byte[15];
                  String data,data1;
                  System.out.println("Flag Value "+flag);

                  try
                  {
                        while(flag == true)
                        {
                              by = new byte[15];
                              dp = new DatagramPacket(by,by.length);

                              d.receive(dp);

                              StringTokenizer st = new StringTokenizer(new String(dp.getData()));
                              data = st.nextToken(":");
                              data1 = (st.nextToken()).substring(0,1);

                              System.out.println("Received "+data+" from Member "+data1+" from port "+dp.getPort());
                              if(data.equals("ELECTION"))
                              {
                                    if((Integer.parseInt(data1)) > val)
                                    {
                                          by = (c2 + ":" +((new Integer(val)).toString()) ).getBytes();
                                          dp1 = new DatagramPacket(by,by.length,inet,dp.getPort());
                                          System.out.println("Sent "+c2+" to Member "+(dp.getPort()-2000)+" on port "+dp.getPort());
                                          d.send(dp1);
                                          head = false;
                                    }
                                    else
                                    {
                                          by = (c3 + ":" + ((new Integer(val)).toString()) ).getBytes();
                                          dp1 = new DatagramPacket(by,by.length,inet,dp.getPort());
                                          System.out.println("Sent "+c3+" to Member "+(dp.getPort()-2000)+" on port "+dp.getPort());
                                          d.send(dp1);
                                    }

                                    if((head == false) && (elect == 0))
                                    {
                                          readMember.execute();
                                    }

                              }
                              else if(data.equals("OK"))
                              {
                                    count_ok++;
                              }
                              else if(data.equals("DENY"))
                              {
                                    count_nook++;
                                    head = false;
                              }
                              else if(data.equals("UP"))
                              {
                                    if( dp.getPort() != ((Integer)array_port.get(dp.getPort()-2000)).intValue() )
                                    {
                                          array_port.set(dp.getPort()-2000,new Integer(dp.getPort()));
                                          by = ("UP"+":"+(new Integer(val)).toString()).getBytes();
                                          dp1 = new DatagramPacket(by,by.length,inet,dp.getPort());
                                          System.out.println("Sent UP to Member "+(dp.getPort()-2000)+" on port "+dp.getPort());
                                          d.send(dp1);
                                    }

                              }
                              else if(data.equals("DOWN"))
                              {
                                    array_port.set(dp.getPort()-2000,new Integer(dp.getPort()-2000));
                                    readMember.execute();
                              }

                              if((count_nook == 0) && (count_ok == 4))
                              {
                                    head = true;
                                    count_ok = 0;

                              }

                              if((data.equals("ELECTION")) && (head == true))
                                    System.out.println("SORRY BUDDY!. I AM THE COORDINATOR. CANNOT GIVE IT TO YOU");
                              else if((data.equals("UP")) && (head == true))
                                    System.out.println("FOR UR KIND INFO,I AM THE COORDINATOR IN HERE");
                              else if((answer.equals("start")) && (head == true))
                                    {System.out.println("WOW! I BECAME THE COORDINATOR");answer = ""; }
                              else if(head == true) System.out.println("I AM STILL THE COORDINATOR");



                        }

                  }
                  catch(Exception e) {System.out.println("last statement\n");System.out.println(e);}
            }
      }


}

Thanks and regards.,
PG
prashanth_gurijalaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

petmagdyCommented:
could u please post the exception stack trace
0
petmagdyCommented:
initially I would change a line in ur execute fucntion like this:

>> j = ((Integer)array_port.get(i-2000)).intValue();

Integer integer = (Integer)array_port.get(i-2000);
if(integer != null)
{
 j = integer.intValue();
}

also please make any updates to the array_port synchronized like this:

public synchronized addToPorts(int index, Object)
 {
  array_port.add(index,Object);

}

public synchronized setToPorts(int index, Object obj)
 {
    Object obj = array_port.get(index);
    if(obj == null)
      array_port.add(index,Object);
   else
    set(index,obj);

}

use those methods whenever add or set in ur array_port



0
prashanth_gurijalaAuthor Commented:
byte by = new byte[100];
dp = new DatagramPacket(by,by.length);
d.receive(dp);

where d is datagram socket as can be seen
and dp is datagrampacket....

these three lines are generating that exception and this is driving me crazy...


0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

petmagdyCommented:
ok i got ur problem:
>> byte by = new byte[100];
should be:

byte[] by = new byte[100];

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MogalManicCommented:
The problem is that you are initializing the field
  DatagramSocket d;
in the Server class which is running in a thread and then trying to access the same variable in the Client class.

I would recommend initializing all of the main class members BEFORE starting the threads.
0
logicbodCommented:
I would change your catch block to

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

then it should be very easy to figure out exactly why the null pointer occurs.
0
petmagdyCommented:
Venabili,

My comment highlighs an obvoius reason for the null pointer exception, I think I deserve that my comment to be accepted or part of the points split
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.