0

I am trying to run this

package mine;

public class MyFantasticJavaClass {

    private static String[] myotherarray;
    public static void main(String[] args) {
        String[] myarray = {"ball","pen","is","large"};
        for(int i=0;i<myarray.length;i++){
            myarray[i] = myotherarray[i];
        }
    }
}

But it does not work no matter what I try.

Can you help me please?

error is

Exception in thread "main" java.lang.NullPointerException
at mine.MyFantasticJavaClass.main(MyFantasticJavaClass.java:9)
Mary
  • 41
  • 3

4 Answers4

2

You havent initialised myotherarray

Your array must follow the format String[] myotherarray = new String[length] before you can add anything too it.

To save you from further errors; you can't read the field myotherarray from the static main method the way you have tried because the static method will not run an instantiation of MyFantasticJavaClass which is required for the field myotherarray

What you would have to do is add to the main method;

 MyFantasticJavaClass name =  new MyFantasticJavaClass()        

     String[] myarray = {"ball","pen","is","large"};

     name.myotherarray = new String[myarray.length];

     for(int i=0;i<myarray.length;i++){
        myarray[i] = name.myotherarray[i];
     }

Assuming that the purpose was just to copy all the elements from one to the other, at present you can't declare it in situ without either moving it out of field into the main, or the other array from the main to the field because once an array is instantiated its length is unchangeable.

davidhood2
  • 1,367
  • 17
  • 47
2

myotherarray has not been initialized so it is equal to null. When you try to do anything with a null variable your JVM (java virtual machine) doesn't know what to do, so it throws the exception. So you should initialize the array like this:

private static String[] myotherarray = new String[5]; // change '5' to however many Strings you want your list to hold.

You might want to read what is a null pointer exception for greater understanding.

Community
  • 1
  • 1
BitNinja
  • 1,477
  • 1
  • 19
  • 25
1

You need to initialize myotherarray before you can read from it. When you say myarray[i] = myotherarray[i];, myotherarray has not yet been set to be anything. What value are you expecting to read from it here?

Levi Lindsey
  • 1,049
  • 1
  • 10
  • 17
0

try this

package mine;

public class MyFantasticJavaClass {

    private static String[] myotherarray;
    public static void main(String[] args) {
        String[] myarray = {"ball","pen","is","large"};
        myotherarray = new String[myarray.length]; //myarray.length is the size of the "other" array
        for(int i=0;i<myarray.length;i++){
            myarray[i] = myotherarray[i];
        }
    }
}

in Java and other languages you always have to initialise variables. Its this "myotherarray = new String[...];"

Neifen
  • 2,546
  • 3
  • 19
  • 31