Saturday, November 17, 2018

java - How can i avoid ArrayIndexOutOfBoundsException in this case?




Is it possible to avoid ArrayIndexOutOfBoundsException in this case ??



package com;

public class Hi {

public static void main(String args[]) {


String[] myFirstStringArray = new String[] { "String 1", "String 2",
"String 3" };

if (myFirstStringArray[3] != null) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}

}


}

Answer



Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?



if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");

}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...