본문 바로가기
Java/Java with Error

[해결 방법] java.lang.NullPointerException

by HJ0216 2023. 2. 11.

 기본 환경: IDE: Eclipse, Language: Java

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class Exam {
	private char[] ox=null;

	public void compare() {
		for(int i=0; i<JUNG.length(); i++) {
			if(dap.charAt(i)==JUNG.charAt(i)) {
				ox[i] = (char)'O';
			} else {ox[i] = (char)'X';}
		} // for
	} // compare
}

Exception in thread "main" java.lang.NullPointerException: Cannot store to char array because "this.ox" is null

→ NullPointerException 발생

 

 

Exception 원인

char[]를 선언 후, 배열의 크기를 지정해주는 초기화 작업을 진행하지 않음

 

 

해결 방법

public class Exam {
	private char[] ox=null;

	public void compare() {
    ox = new char[JUNG.length()];
    
		for(int i=0; i<JUNG.length(); i++) {
			if(dap.charAt(i)==JUNG.charAt(i)) {
				ox[i] = (char)'O';
			} else {ox[i] = (char)'X';}
		} // for
	} // compare
}

/*
Result
O	X	X	O	O
*/

ox = new char[JUNG.length()];

: ox 배열에 대해 크기 지정

 

 

 

참고 자료

📑 why can't I assign null to a particular index of Char Array?

📑 Primitive Types

📑 charGPT