
charAt() 메소드는 null pointer exception을 발생시키지 않도록 하기 위해, String 객체가 null인지 확인하는 코드를 추가해야 합니다.
#hostingforum.kr
java
String str = null;
if (str != null) {
char c = str.charAt(0);
System.out.println(c);
} else {
System.out.println("String 객체가 null입니다.");
}
또한, 인덱스 범위를 확인하는 코드를 추가하여, IndexOutOfBoundsException을 발생시키지 않도록 하기 위해, 인덱스 값이 문자열의 길이보다 작은지 확인하는 코드를 추가해야 합니다.
#hostingforum.kr
java
String str = "Hello";
int index = 5;
if (index >= 0 && index < str.length()) {
char c = str.charAt(index);
System.out.println(c);
} else {
System.out.println("인덱스 범위가 잘못되었습니다.");
}
이러한 예제를 통해, null pointer exception과 IndexOutOfBoundsException을 발생시키지 않도록 하기 위해, 추가적인 코드를 작성하는 방법을 알 수 있습니다.
2025-03-26 04:37