首頁  >  文章  >  Java  >  在Java中,StringIndexOutOfBoundsException是什麼意思?

在Java中,StringIndexOutOfBoundsException是什麼意思?

WBOY
WBOY轉載
2023-09-05 13:29:06847瀏覽

在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)

以上是在Java中,StringIndexOutOfBoundsException是什麼意思?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除