public class Learner {
public static void main(String[] args) {
String[] dataArr = new String[4];
dataArr[1] = "Bill";
dataArr[2] = "Steve";
dataArr[3] = "Larry";
try{
for(String data : dataArr){
System.out.print(data+" ");
}
}catch(Exception e){
System.out.println(e.getClass());
}
}
}
책에 다음과 같이 인쇄됩니다. null Bill Steve Larry
이것은 null로 데이터에 액세스하면 NullPointerException이 발생한다고 생각했기 때문에 혼란 스럽습니다. null 값이있는 배열에 액세스 할 때 예외가 발생하는 경우가 있습니까?
아니면 system.out.println (), 구원의 은혜입니까? data.length ()를 호출하지 않는 한 for 루프로 null 값에 액세스 할 수 있습니까?
문자열 연결은 JLS 에서 피연산자가 null 참조 일 때 안전한 작업 으로 정의됩니다. 즉, 예외 (를 사용하여 객체를 설명하려는 경우에 해당)를 throw하지 않고 대신 .toString()
텍스트를 "null"
사용해야합니다.
개봉이 필요한 경우 안전 검사가 실행 되지 않습니다 .
Integer val = null;
int err = val + 1; // throws NPE
호기심을 위해 null 참조에 대한 정적 메서드에 액세스하는 것은 컴파일 타임에 바인딩이 발생하기 때문에 확인이 필요하지 않습니다.
public class NullRefStatic {
public static void test() { // <-- static method
System.out.println("It works");
}
public static void main(String... args) {
NullRefStatic target = null;
target.test(); // <-- Prints "It works"
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다