I have a class called user that contains the the two variables name and age.
package test;
public class user {
String name;
int age;
}
Then in my main.java i'm creating an array of that class type.
package test;
public class main {
public static void main(String[] args) {
user[] array = new user[2];
array[0].name = "ryan";
array[0].age = 18;
array[1].name ="Ryan";
array[1].age = 17;
for(int i = 0; i < 1; i++){
System.out.println(array[i].name);
System.out.println(array[i].age);
}
}
}
However i get this error.
Exception in thread "main" java.lang.NullPointerException
at test.main.main(main.java:5)
Any help?
5 Answers 5
user[] array = new user[2];
is just a definition of array but the elements of arrays are NOT initialized/are NULL. Hence accessing an attribute or method will result in NullPointerException. You should initialize array element before using them, like this:
array[0] = new user();
array[1] = new user();
Comments
References are initialized to null by default in Java - JLS:
For all reference types (§4.3), the default value is null.
So writing array[0].name = "ryan"; is like writing null.name = "ryan"; which causes the exception.
You should initialize each object in the array. Also please follow Java Naming Conventions and change user to User.
Comments
You need to make "new" objects too. Only the array is not sufficient
Comments
You created only place for two Users. Write:
array[0] = new User();
And your example will work for you:
public static void main(String[] args) {
User[] array = new User[2];
array[0] = new User();
array[0].name = "ryan";
array[0].age = 18;
array[1] = new User();
array[1].name ="Ryan";
array[1].age = 17;
for(int i = 0; i < array.length; i++){
System.out.println(array[i].name);
System.out.println(array[i].age);
}
}
Comments
There is no object to assign a value to at
array[0].name = "ryan";
All you have is an array of variables that nothing has been assigned to as yet. You need to create one first for each address in the array...
array[0] = new user();
then set it's name.
Also, class names should be uppercase User, not user
Lastly, if you are stepping through an array you are better to use it's size rather than a hard coded number
for(int i = 0; i < array.length; i++)
Better yet, do a for-each
for (user u : array) //for each user in array
{
System.out.println(u.name);
System.out.println(u.age);
}
array[0] = new user(). Creating a box that can contains balls doesn't means that there is balls inside.