-3

I'm trying to get the length of a row of a square 2d array, of which I have set the size using this method:

public static void create (String[][] x, int y) {
    x = new String[y][y];
}

The error that shows up is "Null Pointer Exception", and I know that I can fix this issue by just getting rid of the arguement and just using the 2d array variable I want to change in the method, but I just wanted to know if there was a way to get around the error.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 5
    Just FYI, what you try to do is impossible, have a look at: [Is Java pass by reference or pass by value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Lino May 25 '18 at 08:17
  • dangit, was worth at try tho – Fake Persimmons May 25 '18 at 08:17

1 Answers1

0

As I already said in the comments, what you try to do is impossible. If you still want a factory method you change the method:

public static void create (String[][] x, int y) {
    x = new String[y][y];
}

To the following:

public static String[][] create (int y) {
    return new String[y][y];
}

Which will create an 2D quadratic array with the length y. This can be used like shown in the following snippet:

String[][] myArray = create(32);

Which will act equal to:

String[][] myArray = new String[32][32];

And in my opinion the latter is much clearer. Adding a method for such a small array creation is probably overengineered. Even if you have to create like 200 array instances. It will be much clearer if you use the array creation syntax (new String[][]) inline.

Lino
  • 19,604
  • 6
  • 47
  • 65