program_language 및 궁금한것/Java

[자바] NullPointerException 발생원인

jinsiri 2019. 4. 19. 15:25

NullPointerException 발생원인

null이란? 메모리가 할당되지 않은 것.

메모리 할당을 하지 않은 상태에서 필드 또는 메소드를 참조했을 때 발생하는 에러이다!

null.필드명     null.메소드명() ; 발생

ex) 현대아파트에 있는. siri나와라 <- 현대아파트.siri()

 

Q.

aa.bb(dd)

NullPointerException 발생시킬수 있는 요소는? aa

class A {
	void hello() {

	}
}

class Test {
	A a;// null

	void print() {
		a.hello(); // <--null.hello() <-- NullPointerException발생

		a = new A(); // a에는 메모리 주소정보가 저장
		a.hello(); // 실행 Ok
	}

	public static void main(String[] args) {
		Test t= new Test();
		t.print();
	}
}

 

null.bb(dd);  <-- 예외발생!

aa.bb(null);  <-- 예외 발생하지 않음

반응형