특별한 일상

[Java] static변수, non-static 변수 본문

IT•개발 끄적/Java

[Java] static변수, non-static 변수

소다맛사탕 2025. 4. 10. 17:29
반응형

 

안녕하세요. 소다맛사탕입니다.

Java를 사용해서 전역변수를 선언하는 과정에서 static과 non-static을 선언했을 때의 차이점과 설명을 하고자 합니다.

https://develop-sense.tistory.com/entry/JAVA-static-final-%EC%83%81%EC%88%98

 

[JAVA] static, final, static final(상수) 사용법 및 예시

안녕하세요. 소다맛사탕 입니다. 한 번 초기값이 저장되면 변경할 수 없는 불변의 상수인 'static final'에 대해서 알아보겠습니다. 그전에 static과 final의 간단한 설명과 사용법을 알아보겠습니다. 1

develop-sense.tistory.com

이전 static, fianl, static final 사용법을 참고하세요.


static 변수와 non-static 변수의 차이

 

  • static

클래스 수준에서 공유. 모든 객체가 동일한 메모리를 참조하며, 값 변경 시 모든 객체에 영향을 미침.

- 클래스가 로드될 때 메모리가 할당되고 프로그램 종료 시까지 유지됨.

- 클래스 이름으로 직접 접근할 수 있음.

 

public class StaticExam {
    private static List<String> result = new ArrayList<>();

    public static void addVal(String value) {
        result.add(value);
    }

    public static void printValues() {
        System.out.println(result);
    }

    public static void main(String[] args) {
        StaticExam.addVal("A");
        StaticExam.addVal("B");
        StaticExam.printValues(); 			// 출력: [A, B]

        StaticExam instance = new StaticExam();
        instance.addVal("C");
        instance.printValues(); 			// 출력: [A, B, C]
    }
}
  • 모든 객체가 result를 공유
  • 값 추가 시 모든 객체에서 동일한 결과를 확인 가능

  • non-static

- 객체 수준에서 관리. 각 객체는 고유한 메모리를 가지며, 값 변경이 해당 객체에만 영향을 미침.

- 객체 생성 시 메모리가 할당되고 해당 객체가 가비지 컬렉션이 될 때 소멸.

- 객체를 생성한 후 참조를 통해 접근해야 함.

public class NonStaticExam {
    private List<String> result = new ArrayList<>();

    public void addVal(String value) {
        result.add(value);
    }

    public void printValues() {
        System.out.println(result);
    }

    public static void main(String[] args) {
        NonStaticExam instance1 = new NonStaticExam();
        instance1.addVal("A");
        instance1.printValues(); 		// 출력: [A]

        NonStaticExam instance2 = new NonStaticExam();
        instance2.addVal("B");
        instance2.printValues(); 		// 출력: [B]
    }
}
  • 각 객체가 독립적인 result를 가짐
  • 다른 객체의 변경 사항은 영향을 주지 않는다.

 

차이점

 

특징 static 변수 non-static 변수
메모리 위치 클래스 영역(Method Area) 힙 영역(Heap)
공유 여부 모든 객체가 공유 각 객체가 독립적으로 관리
초기화 시점 클래스 로드 시 초기화 객체 생성 시 초기화
접근 방식 클래스 이름으로 직접 접근 가능 객체 참조를 통해 접근 가능

 

따라서,

static 변수를 사용하면 데이터를 모든 인스턴스에서 공유해야 할 때 유용합니다.

(전역 설정, 카운터 etc...)

non-static 변수를 사용하면 각 객체가 고유한 데이터를 유지해야 하는 경우 적합

(사용자별 데이터)

 

참고 : 

https://velog.io/@limjaewoo/Java-static

https://www.baeldung.com/java-static

 

 

Comments