-2

I want to understand how char stores in 2xn char matrix

For example

 int numWords = in.nextInt();
 char[][] words = new char[numWords][];

In above code, words is char matrx which can store numWords number of rows and n number of columns in every row. Correct ?

for (int i = 0; i < numWords; i++) {
                words[i] = in.next().toCharArray();
                System.out.println("in.next().toCharArray():"+words[i][i]);

            }

If I run above code with numWords is equals to 1 and having value a 1

Then how the char array returned by in.next().toCharArray() will save into words char matrix ?

How matrix will look like ?

Update:

With numWords equals to 1 If an char array is having value a, ,1 and print like this

System.out.println("Values:"+words[i][i] + "------"+words[i][i+1]);

Why its showing below error ? In first row there should be 3 columns ?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException : 1
Maria
  • 452
  • 1
  • 6
  • 20
  • *How matrix will look like ?* -> print it using `System.out.println(java.util.Arrays.toDeepString(words));` – Lino Mar 26 '20 at 13:02

1 Answers1

1

Java has no matrix or multidimensional array concept. What you have is an array of arrays, and nothing forces the "internal" arrays to have the same shape (length).

"Array of arrays" means it's an array, where the elements themselves are arrays.

You could visualize the array of arrays like this:

0: **********
1: **
2: ******
3: ***************

When you write

char[][] words = new char[numWords][];

you're creating an array, where the elements are arrays of char, and initially set to null. When you write

words[i] = in.next().toCharArray();

you're making the array element at index i point to a new char array.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Addition: Arrays which are not rectangular are named [*Jagged arrays*](https://stackoverflow.com/q/18269123/5515060), which is the "default" for arrays in java – Lino Mar 26 '20 at 13:06
  • it's better to post a new question instead of changing the question to ask something new @maria that way you'll get answers from more people – Joni Mar 26 '20 at 14:47