首页 > 文章列表 > 在Java中,StringIndexOutOfBoundsException是什么意思?

在Java中,StringIndexOutOfBoundsException是什么意思?

意义 Java中的String StringIndexOutOfBoundsException
108 2023-09-04

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

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

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

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

String str = "Hello";

其中的字符被定位为 −

在Java中,StringIndexOutOfBoundsException是什么意思?

如果您尝试访问字符串中索引大于其长度的字符,则会抛出 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));
      }
      //Accessing element at greater than the length of the String
      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)