Sandeep Raj Urs Sandeep Raj Urs - 10 days ago 6
Java Question

Getting null pointer exception. Not able to print the Array list data in Testing method

public class Test3 {

public ArrayList<String> list;

//storing all data in this lsit

//test() is main test method where program gets triggered

@Test
public void test(){
list=new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
Testing t=new Testing();
//creating object to call testmtd
t.testmtd();
System.out.println(list);
}
}

public class Testing {
public void testmtd()
{
Test3 t=new Test3();
//created object to access list of Test3 class

System.out.println("run1");
for(int i=0;i<=t.list.size();i++)
{
String data=t.list.get(i);
//here i am not able to access the data present in the list of Test3 class
System.out.println(data);
}
}
}

Answer

Test3.test() calls Testing.testmtd(). That function creates a new Test3, and that object has a null list.

You could modify the testmtd function to accept a Test3 parameter:

public void testmtd(Test3 t)  
{   
    System.out.println("run1");
    for(int i = 0; i < t.list.size(); i++) {  // Fixed the out of bounds issue
        String data=t.list.get(i);  
        System.out.println(data);
    }
}

Then, modify the way it's called:

public void test() {
    list=new ArrayList<String>(); 
    list.add("1");
    list.add("2");
    list.add("3");
    Testing t=new Testing(); 
    t.testmtd(this);     // Pass this object
    System.out.println(list);
}