Saturday, 17 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...