Following code is for deleting elemnt from array but it shows NullPointerException at if(names[k].equals(user)) ... how to remove it!!!

public class del_array {

    public static void main(String s[])
    {  
      String names[ ] = new String [10];

        names[0]="admin";
        names[1]="b";
        names[3]="m";


        String user="b";

        for(int k=0;k<names.length;k++)
      {
          if(names[k].equals(user))
          {
              String item=names[k];
              for(int j=k;j<names.length-1;j++)
                {
                     names[j]=names[j+1];
                 }

          }

     }

Recommended Answers

All 3 Replies

When you initialize an array via the = new <TYPE>[]; method, the array is created, but the objects are not. This means that when you try to run methods on them, like in line 16, they will throw a NullPointerException. If you initialize them (in a loop or otherwise), the Exception should be removed. Good Luck!

jackmaverick1 has the right answer. The value of names.length is 10, so your program is exploding when k==4.

Consider using a java.util.ArrayList<String> instead.

or add a break statement once you've found the name.

another possibility would be:

if ( names[k] != null && names[k].equals(user)){
....
}

this way you'll only call the equals on it if it isn't null, and that way, you avoid the nullpointerexception

commented: thanksss :) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.