Java 中的 StringIndexOutOfBoundsException 是什么?

javaobject oriented programmingprogramming

Java 中的字符串用于存储字符序列,它们被视为对象。java.lang 包的 String 类表示一个字符串。

您可以使用 new 关键字(像任何其他对象一样)或通过为文字分配值(像任何其他原始数据类型一样)来创建字符串。

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

由于字符串存储的是字符数组,就像数组一样,每个字符的位置都由索引表示(从 0 开始)。例如,如果我们创建了一个字符串作为 −

String str = "Hello";

其中的字符定位为 −

如果您尝试访问索引大于其长度的字符串的字符,则会抛出 StringIndexOutOfBoundsException

示例

Java 中的 String 类提供了各种方法来操作字符串。您可以使用此类的 charAt() 方法在特定索引处找到字符。

此方法接受指定字符串索引的整数值,并返回字符串中指定索引处的字符。

在下面的 Java 程序中,我们创建一个长度为 17 的字符串并尝试打印索引为 40 的元素。

public class Test {
   public static void main(String[] args) {
      String str = "Hello how are you";
      System.out.println("Length of the String: "+str.length());
      for(int i=0; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
      //访问大于字符串长度的元素
      System.out.println(str.charAt(40));
   }
}

输出

运行时异常 −

由于我们访问的元素的索引大于其长度,因此会引发 StringIndexOutOfBoundsException。

Length of the String: 17
H
e
l
l
o
h
o
w
a
r
e
y
o
u
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 40
   at java.base/java.lang.StringLatin1.charAt(Unknown Source)
   at java.base/java.lang.String.charAt(Unknown Source)
   at Test.main(Test.java:9)

相关文章