0

So i'm working on a program in Java, and whenever i run it, i get an error "Exception in thread "main" java.lang.NullPointerException". When i look at it closely, it appears that its caused by array of Reference Variables. Here's the code causing the problem:

    public class agendafunctions {
static String input = "true";
agendaitem item[] = new agendaitem[5];
public agendafunctions() {
    item[0].name = "one";
    item[1].name = "two";
    item[2].name = "three";
    item[3].name = "four";
    item[4].name = "five";
}

name is a variable in class agendaitem. From what i've read elsewhere, the error is caused by the program trying to use variables with a null value. But when i add a value, it says it can't convert from String or whatever to type agendaitem. Can anyone help?

1
  • Please stick to Java conventions and start class names with capital letters. Small letters are for variables and methods! Commented Sep 1, 2013 at 1:40

2 Answers 2

8

You need to instantiate those objects first. Declaring an array of objects just gives you an array of nulls. Trying to set properties on those nulls will give you a NullPointerException.

Before setting any names, you need to run:

for (int i = 0; i < item.length; i++)
    item[i] = new agendaitem();

Also, you should change you class name to AgendaItem to observe proper Java style.

Sign up to request clarification or add additional context in comments.

Comments

0

Try adding this before you use them:

for(int i = 0; i< item.length; i++) {
    item[i] = new agendaitem();
}

When you create an array of an object, all of its values are null (primitives are the default primitive value). You must initialize each index manually (or through a loop) before using it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.