Java – how to avoid ArrayIndexOutOfBoundsException in this case?
•
Java
See English answers > what causes a Java lang.ArrayIndexOutOfBoundsException and how do I prevent it? 23
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"); } } }
Solution
Maybe I don't understand the real problem, but in this case, what prevents you from checking whether the index is in the array before accessing it?
if (myIndex < myFirstStringArray.length) { System.out.println("Present"); } else { System.out.println("Not Present"); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码