how to solve java.lang.NullPointerException

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vikassawant
    New Member
    • Mar 2009
    • 27

    how to solve java.lang.NullPointerException

    hi,
    when I execute following code, I get the java.lang.NullP ointerException

    try
    {

    int cnt=0;
    for(int i=0;i<d;i++)
    {
    String s = dpos[i];
    String s1 = dpos1[i];
    String s2 = dpos2[i];
    String s3 = dpos3[i];

    if(s.equals("C" ) || s1.equals("C") || s2.equals("C") || s3.equals("C"))
    {
    cnt++;
    cfn[i] = dfn[i];
    cln[i] = dln[i];
    cpos[i] = dpos[i];
    chr[i] = dhr[i];
    crbi[i] = drbi[i];
    csb[i] = dsb[i];
    cavg[i] = davg[i];
    cvalue[i] = dvalue[i];
    }

    }

    for(int c=0;c<cnt;c++)
    {
    System.out.prin tln("Selected Players for C Position are:"+cfn[c]+" "+cln[c]);
    }


    }
    catch(Exception e)
    {
    System.out.prin tln("Exception is....."+e);
    }

    but when I execute above code by making change in only if condition like

    if(s.equals("C" ) )

    it works well.But I want to check for all four string.

    What mistake is here due to which I get the above exception.

    Thanks,
    Vikas Sawant.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    In your catch clause change your print statement to "e.printStackTr ace()" and you'll see exactly on what line you tried to dereference a null reference.

    kind regards,

    Jos

    Comment

    • vikassawant
      New Member
      • Mar 2009
      • 27

      #3
      thanks Jos,

      I change exception according to you...
      I get the error at same line which I told above... i.e.

      if(s.equals("C" ) || s1.equals("C") || s2.equals("C") || s3.equals("C"))

      but when I change this loop like

      if(s.equals("C" ))

      It works.

      Please tell me what can I do.

      Thanks,
      Vikas Sawant.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by vikassawant
        thanks Jos,

        I change exception according to you...
        I get the error at same line which I told above... i.e.

        if(s.equals("C" ) || s1.equals("C") || s2.equals("C") || s3.equals("C"))

        but when I change this loop like

        if(s.equals("C" ))

        It works.

        Please tell me what can I do.

        Thanks,
        Vikas Sawant.
        At least one of s1, s2 or s3 are equal to null then. You have to reason 'backwards' in your code and see what caused it. A few System.out.prin tln( ... ) method calls sprinkled in may be of help.

        kind regards,

        Jos

        Comment

        • r035198x
          MVP
          • Sep 2006
          • 13225

          #5
          There is also a whole article devoted to that exception alone.

          Comment

          Working...