0

I am having null pointer exception. Could you please assist me? I am having problems with objects in the Array list. I don't know where is the issue.

  • Main Class

    public class JavaApplication3 {

     public static void main(String[] args) {
    
    
         ArrayList<user> object=new ArrayList<user>();
    
       user[] obj=new user[3];
    
        obj[0].setName("S");
    
        obj[0].setNumber(5);
    
          obj[1].setName("7");
    
        obj[1].setNumber(6);
         object.add(obj[0]);
    
           object.add(obj[1]);
        System.out.println(object.get(0).getName());
        System.out.println(object.get(1).getName());
    
    
    
    
    
     }
    

    }

  • And this is my user class:

    public class user {

     private int no;
     private String name;
    
       public int getNo() {
         return this.no;
     }
    
     public void setNumber(int no) {
         this.no = no;
     }
    
    
     public String getName(){
    
     return this.name;
     }
    
     public void setName(String S){
    
         this.name=name;
    
     }
    

    }

AND THIS IS MY ERROR:

Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
Exception in thread "main" java.lang.NullPointerException
    at javaapplication3.JavaApplication3.main(JavaApplication3.java:26)
C:\Users\User\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\User\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:68: Java returned: 1
BUILD FAILED (total time: 0 seconds)

1 Answers1

0

just convert this from S to name

 public void setName(String name){
    
        this.name=name;
    
    }

and change to this code

ArrayList<user> object=new ArrayList<user>();
 user[] obj=new user[3]; 
obj[0]=new user(); 
obj[2]=new user(); 
obj[0].setName("S"); 
obj[0].setNumber(5);
 obj[1]=new user(); 
obj[1].setName("7");
 obj[1].setNumber(6); 
object.add(obj[0]); 
object.add(obj[1]);
 System.out.println(object.get(0).getName()); System.out.println(object.get(1).getName());