Java/[국비] JAVA

[국비][JAVA] 메모리 영역_예시를 통한 이해(1) 및 NullPointerException 예제 보기

줌인. 2024. 6. 5. 23:36

▶ 자바 메모리 영역

https://zoooom-in.tistory.com/103

 

[국비][JAVA] 자바 메모리 영역

▶ 참고 (자바 메모리와 static 구조)https://zoooom-in.tistory.com/57 [김영한_자바기본][7. 자바 메모리 구조와 static] 자바 메모리 구조 이해 / 스택과 큐 자료 구조(p.1-메서드 영역: 프로그램의 클래스 정

zoooom-in.tistory.com

 

[예제 코드_WeatherDTO]

public class WeatherDTO {
    private String city;
    private double gion;
    private String status;
    private int humidity;

    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public double getGion() {
        return gion;
    }
    public void setGion(double gion) {
        this.gion = gion;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public int getHumidity() {
        return humidity;
    }
    public void setHumidity(int humidity) {
        this.humidity = humidity;
    }
}

 

[예제 코드_WeatherService]

public class WeatherService {
    private StringBuffer sb;

    public WeatherService() {
        this.sb = new StringBuffer();
        this.sb.append("서울 , 29.3 - 맑음 - 60");
        this.sb.append("- 부산 , 33.6 - 흐림 - 90");
        this.sb.append("- 제주 , 26.5 - 눈 - 30");
        this.sb.append("- 광주 , 10.6 - 태풍 - 80");
    }

    public WeatherDTO[] init() {
        String info = this.sb.toString(); //StringBuffer -> String type으로 변환
        info = info.replace(",", "-"); //StringBuffer에 들어갔던 ","을 "-"로 변환
        WeatherDTO [] dtos = this.getWeathers(info);
        return dtos;
    }

    private WeatherDTO [] getWeathers(String info) {//초기StringBuffer에 있던 내용 16개
        //16개를 기반으로 배열 생성할 것.
        String [] infos = info.split("-"); 
        int idx = 0;
        WeatherDTO [] dtos = new WeatherDTO[infos.length / 4]; //16개 중 4씩 나눠서 배열에 담고 싶음
        //배열이 있으면 배열안에 객체가 있어야 함
        //dtos[0].getCity()를_dtos 0번째에 있는 겟 시티에 접근한다를 하면 nullPointerException이 뜸
        //이유는 dtos 배열 선언만 한 상태, 초기화가 되어있지 않음. 즉 null 상태
        //dtos[0] == null, 즉 null에 접근하면 데이터를 확보할 수 없다.

        for(int i = 0; i < dtos.length ; i++ ) {
            WeatherDTO w = new WeatherDTO(); //객체생성 
            //따라서 WeatherDTO[] 배열이기에 WeatherDTO 타입을 가진 객체를 주면, 객체의 세부 주소에 접근 가능하다.
            w.setCity(infos[idx++].trim());
            w.setGion(Double.parseDouble(infos[idx++].trim()));
            w.setStatus(infos[idx++].trim());
            w.setHumidity(Integer.parseInt(infos[idx++].trim()));
            dtos[i] = w;
        }
        return dtos; //값을 넣은 배열 반환
    }
}

 

[WeatherService 메모리 생성 구조 도식화]

- 리턴받지 못하는 값은 사라지며, 리턴받는 값은 메서드가 사라짐에도 불구하고 재사용할 수 있음

- 배열 자체를 생성할 경우 초기값을 대입하지 않았기 때문에 null이 발생

- 객체에 특정 요소에 접근하고 싶을 경우는 객체 생성이 이루어져야 함

 


[NullPointerException 발생 원인 이해하기]

- Java에서 배열을 선언하면 메모리 공간만 할당되고, 각 요소는 기본값으로 초기화

 ex) 예를 들어, int 배열은 0으로, 객체 배열은 null로 초기화됨

String[] names = new String[3];
names[0].length(); // NullPointerException 발생

 

- 이 코드에서 names[0]은 초기값 null을 가짐

- length() 메서드를 호출하려 할 때 NullPointerException이 발생

- 배열의 각 요소를 사용하기 전에 반드시 초기화해야 함

 

names[0] = "Alice";

- 이렇게 하면 names[0]은 더 이상 null이 아니므로 안전하게 메서드를 호출할 수 있음

728x90