Home (Java) Null Pointer Exception (NPE)
Post
Cancel

(Java) Null Pointer Exception (NPE)

null로 인해 발생된 에러는 시간이 지날수록, 자신이 개발한 소스가 아닌 경우 더욱 더 디버깅 하기 어려워 진다.

null이 발생하는게 오류가 아닐 수 도 있고, 오히려 참 일수도 있고, null인경우 또다른 어떤 의미를 내포하고 있는지 판단하기 어렵다.

즉, 처음부터 NPE를 발생시키지 않도록 코딩하면 자연스럽게 코드의 품질이 향상될 것 이다.

문자열 비교 시 equlas 문자열을 먼저 위치 하자.(또는 Constants 사용하자)

NPE를 발생할 수 있는 코딩 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String[] args) {

	String a = null;

	System.out.println("1번째============");
	if (a == "god") {
		System.out.println("참");
	} else {
		System.out.println("거짓"); //거짓 출력
	}

	System.out.println("2번째============");
	if (a.equals("god")) { // NPE 발생!
		System.out.println("equals => 참");
	} else {
		System.out.println("equals => 거짓");
	}
}

/******* 결과 *******/
1번째============Exception in thread "main"
거짓
2번째============
java.lang.NullPointerException

a의 변수가 null인경우 “NPE”가 발생한다. null은 객체가 아니기 때문에 당연히 “equlas” 라는 메서드도 없기 때문이다.

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
	String a = null;

	if ("god".equals(a)) { // NPE 발생하지 않음
		System.out.println("equals => 참");
	} else {
		System.out.println("equals => 거짓");
	}
}

/******* 결과 *******/
equals => 거짓

“비교의 주체가 문자열”부터 주어진다면”NullPointException”이발생하지 않는다.결국 순서만 바꿨음에도 적어도”NullPointException”을피할 수 있게 된다.

정리해보면 문자열 비교는”non-null String 기준으로 비교” 하는 것이 좋다.”비교의 주체가 문자열”이 오도록 하거나,”Constants 등을 활용” 하여 코딩 하는 것을 추천 한다. 

toString() 대신 => valueOf() 사용

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
	Integer a = 1;
	System.out.println(a.toString());

	a = null;
	System.out.println(a.toString());
}

/******* 결과 *******/
1
Exception in thread "main" java.lang.NullPointerException
1
2
3
4
5
6
public static void main(String[] args) {
	Integer a = null;
	System.out.println(String.valueOf(a));
}
/******* 결과 *******/
null
This post is licensed under CC BY 4.0 by the author.