+ 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?

2nd Jun 2019, 10:31 AM
Bakar Jokhio
Bakar Jokhio - avatar
3 odpowiedzi
+ 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;
2nd Jun 2019, 10:42 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 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 ;
2nd Jun 2019, 10:45 AM
Théophile
Théophile - avatar
+ 2
Dear friends Thanks both of you. code works
2nd Jun 2019, 11:56 AM
Bakar Jokhio
Bakar Jokhio - avatar