Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 StringIndexOutOfBoundsException이란 무엇입니까?

<시간/>

문자열은 Java에서 일련의 문자를 저장하는 데 사용되며 객체로 취급됩니다. java.lang 패키지의 String 클래스는 String을 나타냅니다.

new 키워드를 사용하거나(다른 객체와 마찬가지로) 문자열을 생성하거나(다른 기본 데이터 유형과 마찬가지로) 리터럴에 값을 할당할 수 있습니다.

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

문자열은 문자 배열을 저장하므로 배열과 마찬가지로 각 문자의 위치는 인덱스(0부터 시작)로 표시됩니다. 예를 들어 문자열을 −

로 생성한 경우
String str = "Hello";

그 안의 문자는 -

로 배치됩니다.

Java에서 StringIndexOutOfBoundsException이란 무엇입니까?

StringIndexOutOfBoundsException 길이보다 큰 인덱스에서 문자열의 문자에 액세스하려고 하면 던져집니다.

문자열 Java의 클래스는 문자열을 조작하는 다양한 방법을 제공합니다. 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)