본문 바로가기

Programming/JAVA

문자변수 비교 방법(Null Point Exception 예방하기)

문자변수를 비교할 때 가끔식 null point exception을 보신적이 있을 겁니다. 이를 예방하는 간단한 방법을 소개하니 참고하세요~

핵심은 문자 변수를 왼쪽이 아닌 오른쪽에 주는 것이니 … 기억 하세요~

1. 아래는 Null Point Exception의 확률이 있죠^^

public void test1() {
if (test.equals("hello"))) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}

2. Null Point Exception을 방지하기 위해 아래처럼 하기도 하죠^^

public void test2() {
if (test != null && test.equals("hello"))) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}

3. 아래는 Null Point Exception에 대해 안전한 방법입니다.!!!

public void test3() {
if ("hello".equals(test)) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}