+ 2
How to Replace existing index in array in Java
https://code.sololearn.com/cECQ7q7Z43V7/?ref=app In above code I tried to replace number 6 with 5, I think which is on index 4 but it is not working. What could be reason?
3 Respostas
+ 9
(intArr.length) is not index of last element, but it is size of array(which is 1 more than index of last element of array)so it is giving IndexOutOfBound exception. You can substract 1 from size of array, to get index of last element.
int x=intArr.length-1;
+ 2
The length of your array is 5.
The issue is that array[5] doesn't exist : the last element is at array[4], because index in arrays starts at 0.
So write :
int x = array.length ;
array[x - 1] = 5 ;
+ 2
Dear friends Thanks both of you. code works