Why is this returned array not working?

In this code I'm trying to pass a two dimensional array of chars into cArray and return a one dimensional array of elements that display a string of each row of the two dimensional array.

Example:

Input array (two dimensonal):

'a' 'b' 'c' 'd'

'e' 'f' 'g' 'h'

'i' 'j' 'k' 'l'

Returned array (one dimensional):

abcd

efgh

ijkl

Here is my code:

Main:

public class hw2p1
{   
   public static void main (String [] args) 
   {

  // declare and initialize array of chars
  char[][] array = { {'a', 'b', 'c', 'd'},
                     {'e', 'f', 'g', 'h'},
                     {'i', 'j', 'k', 'l'} };

  cArray array1 = new cArray(array); 

  String[] array2 = array1.getArray();

  for (int i=0; i<array2.length; i++) 
    System.out.println(i+" "+array2[i]);


  }
}

cArray:

public class cArray
{   

   private String[] newArray;

   public cArray ( char[][] array2 )
   {  
      String[] newArray = new String[array2.length];

      for (int i=0; i < array2.length; i++)
         newArray[i] = String.valueOf(array2[i]);

      for (int l=0; l < array2.length; l++)
         System.out.println(newArray[l]);



   }
   public String[] getArray()
   {
      return newArray;
   }
}

I get this error when I try to run this:

Exception in thread "main" java.lang.NullPointerException at hw2p1.main(hw2p1.java:16)

Sorry if this is an obvious error. I'm very new to programming. Thank you for any help!

Jon Skeet
people
quotationmark

This is the problem:

String[] newArray = new String[array2.length];

That's declaring a local variable in the constructor - so you're not assigning a value to the field at all. You just want:

newArray = new String[array2.length];

Having said that, it's not clear why you need to create an instance for this at all - I'd be tempted to just have a single method with a signature of:

static String[] combineArrays(char[][] arrays)

Then you can use just a local variable, and there'll be no field to worry about at all. This could be in the same class as your main method, too.

people

See more on this question at Stackoverflow