Java uses a custom array to report a null pointer exception

At the beginning, I customized a student class with several attributes. Because there are many students, I want to declare this class as an array, but when I assign values ​​to different objects in the array through different subscripts, I always report a null pointer exception

At the beginning the code is like this

package _4_9_test;

public class EightTwoTest {

	public static class Test{
		   String name;
		   int num;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test test[] = new Test[2];
		
		test[0].name = "张珊";
		test[0].num = 1;
		
		test[1].name = "李四";
		test[1].num = 2;
		
		System.out.println(test[0].name+" "+test[0].num);
		System.out.println(test[1].name+" "+test[1].num);

	}

}



After reading the documentation, I found that the creation of the array does not allocate memory to the members of the array.
Test test[] = new Test[2];

There is no place to store data.


Only after each member declares will this member be allocated memory

test[0] = new Test();

The improved code looks like this

package _4_9_test;

public class EightTwoTest {

	public static class Test{
		   String name;
		   int num;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test test[] = new Test[2];
		
		test[0] = new Test();
		test[0].name = "张珊";
		test[0].num = 1;
		
		test[1] = new Test();
		test[1].name = "李四";
		test[1].num = 2;
		
		System.out.println(test[0].name+" "+test[0].num);
		System.out.println(test[1].name+" "+test[1].num);

	}

}

Guess you like

Origin www.cnblogs.com/lyd447113735/p/12695345.html