Why is this an array out of bounds exception? - java

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.

Related

Java 2D Array rows vs cols syntax question

I am having a hard time understanding why putting brackets versus leaving them out either calls for the rows or cols in a 2D array. I get the syntax I just don't understand why it works that way? Should I just not worry about it and move on with my life?
double[][] values = {
{1.2, 9.0, 3.2},
{8.2, 8.6, -1.2},
{-7.3, 2.5, 9.7},
{4.1, 7.0, 5.1},
};
System.out.println("Number of Rows: " + values.length);
System.out.println("Number of Cols: " + values[0].length);
a 2D array is an array of arrays. The variable length returns the number of elements in the array.
so values.length gives the number of elements in the outer array which are the inner arrays (rows)
and values[0].length gives the number of elements in the first inner array (columns)
values.length gives you the length of the outer array. That is the array containing 4 rows. The outer array happens to contain objects that are themselves arrays.
values[0].length gives you the length of the 1st (0th) object in the outer array. This 1st object is itself an array. Since your 2D array is rectangular, every row has the same number of elements, or columns. So getting the length of any one of them will give you the number of columns
Hope that's clearer!

How to initialise an int java array of size n initially empty?

In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.
//PSEUDO CODE
func(){
//Create array A of max size 5
A[0]=1;
A[1]=2;
A[2]=3;
return A;
}
main(){
int[] B=func();
//B.length should give 3
for (int i=0;i<B.length;i++){
print B[i];
}
/*Should print 1 2 3
and Not 1 2 3 0 0
*/
}
And I don't want to use array list.I want to use java array only.
Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:
for (int i=0;i<B.length;i++){
if (B[i] != 0){
print(B[i]);
}
}
However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:
int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
print(B[i]); //will print "1 2 3"
}
The counter must be incremented everytime you add a value.
Both solutions are limited though, depending on how you access and use the array.
then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let u r adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.

Java code length -1 meaning [duplicate]

This question already has answers here:
Does a primitive array length reflect the allocated size or the number of assigned elements?
(17 answers)
What does arrays.length -1 mean in Java?
(1 answer)
How do you determine the legal index range for an array?
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
class Zillion {
private int zilly[];
public Zillion(int size){
zilly = new int[size];
}
public void increment(){
int i=zilly.length -1;
while(i>=0){
if(zilly[i]!=9){
zilly[i]+=1;
i=-1;
}
else{
zilly[i]=0;
i--;
}
}
}
I just got a basic java code like this and do not know what length -1 means at this part (int i=zilly.length -1;).
Can someone please explain this ?
The size of array is the number of elements in this array, but The first index of arrays is 0. For example :
int zilly[] = {1, 2, 3, 4}
In this example :
zilly.size return : 4
But zilly[4] not exist because the index of the first element is 0
zilly.[zilly.size - 1] return the last element (4).
Hope it helps.
nameOfTable.lenght return the number of element
the first index of Arrays start with 0 ==> (1st - 1 = 0) ,
so the last index is n - 1
int i=zilly.length -1; is the last index of the array, because arrays start at index 0.
A side note, the formatting of this code be improved to better portray what it's doing, for example the line that confused you could be.
int i = zilly.length - 1; simply spacing out the statement correctly makes it a bit easier to understand.
zilly.length -1 defines itself. Total array length (size) -1.
Since the first index of array starts with 0 so the last item is at position n-1 where n is the size of array.
In Java indexing of arrays starts from 0. Therefore the last element of arrays is accessed by zilly[zilly.length - 1]. If you try to access it this way:
zilly[zilly.length]
you will get an out of bounds exception.
The while loop in your code starts from the last index and iterates down the very first element.
zilly.length gives the length of the array, i.e. the number of elements in it.
zilly.length-1 gives the last index of the array because the count of the array begins from 0.
So basically you are iterating in a descending order, i.e. from the last element of the array to the first element of the array.
It means that we want to get the last index in the array.
And then we loop over the array from end to start.
zilly.length it's the array size - but the array's index starts from 0 so the last index is zilly.length-1

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.

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