2D array row and column length - java

I'm studying 2D array right now, there is a part of 2D array I don't really understand. I will show my code and explain what part I don't understand.
My code:
public static void main(String[] args){
int[][]array={{1,2,3},{1,2,3},{1,2,3}};
}
public static printArray(int[][]a){
for(int row=0;row<a.length;row++){
for(int column=0;column<a[row].length;column++)
}
My question is for the second method of printArray. In the second for loop,what does column<a[row].lengthmeans?

This line gives the size of each row.
You know that
a[0]={1, 2, 3}
a[1]={1, 2, 3}
a[2]={1, 2, 3}
So, a[0].length = a[1].length = a[2].length = 3. Use of this is to ensure that we dont go Out Of Array Bounds.

Java doesn't have 2D arrays. Java has arrays of arrays. The second loop uses column < a[row].length to make sure that you don't iterate past the length of the row-th array. You need this to handle nested arrays of varying length.

That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException

A 2D array means that each element of the array is itself an array. The second loop allows you to loop through each {1,2,3} array (in your case). But to do that, you need the length of each array. That's what a[row].length provides.

Related

Why can I not get a one dimensional array of a column as easy as a row?

Background
This is a 2d array.-
String[][] names = { {"Sam", "Smith"}, {"Robert", "Delgro"}, {"James", "Gosling"}, };
I can access the rows by calling this:
names[n]
Where n is any integer between the bounds and in this case 0<=n<=names.length-1.
Likewise
I can call this
String [] rowOne = names[0];
Inquiry
The question now remains,instead of rows, is there a way to access a specific column in the same way a specific row is accessed.
Feedback
I would like feedback on this suggestion.
In the particular case of accessing a column in a 2d array,names[][x]would be the declaration to call a specific column,where 0<=x<=names[0].length-1.
String[] columnOne = names[][0]
This would mean that names.length would be equivalent to calling names[][x].length
This could also work for arrays greater than a 2d array.
String[][][]names = { {{"Sam", "Smith"}, {"Robert", "Delgro"}}, {{"James", "Gosling"}}};
Just add extra square brackets.
For example In a 3d array, to access an aisle, which is what I will refer to the 3rd dimension.
names[][][z], where 0<=z<= names[0][1].length-1
One dimensional arrays from multi-dimensional arrays.
...is there a way to access a specific column in the same way a specific row is accessed.
No; Java's multidimensional arrays are essentially arrays that contain references to other arrays are not contiguous in memory. Java also allows arrays to be jagged. Let's say you have the following multidimensional array:
int[][] array = {
{1, 2, 3},
{4, 5},
{6}
};
By calling array[][2], what would you expect to receive? What about array[][3]?
To be able to get an array of columns, you would need to first transpose the multidimensional array.

Understanding Java sorting

I'm still learning about sorting and Arrays. Came up with this code which does sorting letters or numbers on ascending order but I really don't get the last part where System.out.println(SampleArray[i]);. Why is it SapleArray[i]? can someone enlighten me please.
public class TestClass {
public static void main(String[] args) {
String SampleArray[] = {"B","D","A","R","Z"};
Arrays.sort(SampleArray);
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
}
}
SampleArray refers to the whole array - here containing five strings.
SampleArray[0] refers to the first item in the array (here the string "B").
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
lets i take the values 0, 1, 2, 3, 4 one after another, so you print out first SampleArray[0]and then SampleArray[1] and so on until all the items have been printed.
You are trying to print an array, which is an ordered collection of items.
SampleArray[i] inside the loop lets you access one element at a time, in order.
More specifically, i takes on the values 0 through 4 in this case.
SampleArray[0] would give you the first element of SampleArray, because Java uses zero-based indexing for arrays.
Going through your code:
first you create a String array with those letters as element, which are saved like this: element 0 of array = B, element 1= D, etc. (in Arrays the counting always begin by 0 and not by 1).
Then it sort it in ascending order.
The for loop is there to print the sorted array, it iterate through the array beginning by element 0, until it is at the last element of the Array and it print these element.
The for loop does something over and over again.
The first part of the for loop, int i = 0 sets up a variable.
The second part i < SampleArray.length is the 'terminating condition' - it's the condition that has to remain true before each iteration of the loop.
The last part i++ is what happens after each iteration - i gets incremented.
So we are printing each element within SampleArray. i goes between 0 and the one less than the number of elements in the array. (e.g. if the array contained 4 elements, i would be 0 to 3, which is what we want).
And in the body of the loop, the [i] bit selects that element from SampleArray, and that is the value that gets printed on each line.
Another way of looking at it: SampleArray supports the [] operator, which when applied, will return an element from the array.

Creating a new 2D array that = size of 2D array 1 + size of 2d array 2 (rows and columns)

public static int[][] add2DArrays(int[][]A, int[][]B) {
return int[][] C;
}
I understand how to populate this new array by adding the sums of the two arrays A & B, the road block I am facing is creating this initial array C. We cannot assume the size of the arrays given as parameters, so that is the part I am having a problem with.
I know by doing:
int[][] C = new int[A.length+B.length][]; //this will only give me the # of rows;
I am stuck on how to get the proper length of columns for the rows in the new array. I am thinking it may be possible to some how record the length of the longest row in A, and then record the longest row in B, and choose the bigger of the two, but that seems messy and inefficient. Thank you all for your support.
If both are really 2D arrays -- that is, the length of all the rows is the same -- and row 0 was actually allocated, you can get the summed length of a row from A[0].length+B[0].length
If the length of the rows might vary -- which is perfectly legal in Java -- then you might need to iterate through A and B to find the longest row and use that length.

Why is this an array out of bounds exception?

Why does this cause an array out of bounds exception ?
x[10][2] = 5;
Should this be assigning the 3rd spot of the 11th array, the value 5
I thought of it in a rectangular way.
Its like we have to count 11 rows(representing the 10 arrays)
and then we have to go to the 3rd column that is the 2
OR
I should be looking at it as an array looking for the 11th spot in an array of size 2 that doesn't actually exist ?
Is the 11th element of x an array? If it is, what is its length?
You are receiving that error because it's likely the length of that element is less than 3.
Test it by trying
System.out.printf(x[10].length);
Hope that helps.
Why does this cause an array out of bounds exception?
x[10][2] = 5;
This only happens when you try to access a position out of the range that you had defined for your array. For example
int x[20][20];
You can make x[10][2] = 5; without a problem because 10 < 20 and 2 < 20. But if you did:
x[30][20] = 5;
You would have the out of bounds exception because you are trying to access the position (30,20) of the 2D array, a position that surpasses the size of the 2D array.
It is because x[10][2] does not exist.
It can be either because x[10] is not a valid element (i.e. x.length is equal to or greater than 10), or x[10][2] is not a valid element (i.e. x[10].length is equal to or greater than 2). The exception message tells you which index fails, if they differ.
Note that a multidimensional array doesn't have to be a matrix. This is called a jagged array.
For example, consider the following code (from Wikipedia):
int[][] arr = new int[2][]; // creates 2 rows
arr[0] = new int[3]; // 3 columns for row 0
arr[1] = new int[5]; // create 5 columns for row 1
Referencing arr[0][4] would throw an ArrayIndexOutOfBoundsException, while referencing arr[1][4] would not.
As Mark Stevens already mentioned in the comments, which one is the row and which one the column, is subjective. As opposed to what jazzbassrob says in the comments, Java has neither row-major nor column-major order. In fact, in Java, there is no such thing as a two-dimensional array, instead, it's actually an array of arrays.

How does this Java code work?

public static void main(String[] args)
{
int [][]shatner = new int[1][1];
int []rat = new int[4];
shatner[0] = rat;
System.out.println(shatner[0][3]);
}
surprised, The output is 0, why Java doesn't check this kind of indexOutOfBound error?
Don't be surprised. shatner[0] is an array (rat) and happens to be of length 4. So shartner[0][3] is rat[3] which happens to be 0..
Where do you see an "indexOutOfBound error"? The code does the following:
Initalize an array (size 1) of int arrays (size 1), i.e. a 2D array, contents are intialized with 0
Initalize a array of int, size 4, content is intialized with 0
set the single element of the 2D array to the size 4 1D array
access the last element of the first array in the 2D array, which is 0
There is nothing going out of bounds.
The 0th row in the shatner array gets reinitialized to int[4].
There is no index out of bounds error. shatner is an array of arrays. You replaced the first array of length one with a new one of length four. So now shatner[0][3] is a perfectly legit place in memory.
It's not that Java doesn't check the IndexOutOfBoundsException. It's that the answer SHOULD be zero. The key line is
shatner[0] = rat;
Since that means that the 0th index of shatner is pointing to an array of length 4, shatner[0][4] is totally valid.
I'm thinking it's because java's arrays are working a bit differently than expected. You initialize shatner to [1][1], meaning something like, {{0},{0}} in memory.
However, you then assign an integer to the first element, turning it into {{0,0,0,0},{0}} in memory, so Java is addressing the newly assigned index.
Arrays need not be rectangular in Java. This is a jagged array and is perfectly fine.

Categories