[Development Record:: JAVA] 2. Stack & Heap Memory
자바 기초 용어 정리
객체 : 객체 지향 프로그램의 대상, 생성된 인스턴스
클래스 : 객체를 프로그래밍 하기 위해 코드로 정의해 놓은 상태
인스턴스 : new 키워드를 사용해 클래스를 메모리에 생성한 상태
멤버 변수 : 클래스의 속성, 특성
메서드 : 멤버 변수를 이용하여 클래스의 기능을 구현한 함수
참조 변수 : 메모리에 생성된 인스턴스를 가리키는 변수
참조 값 : 생성된 인스턴스의 메모리 주소 값
Stack과 Heap 메모리 구조
FunctionTest.java
public class FunctionTest {
public static int addNum(int num1, int num2) {
int result;
result = num1 + num2;
return result;
}
public static void sayHello(String greeting) {
System.out.println("greeting");
}
public static int calcSum() {
int sum = 0;
int i;
for(i = 0; i<=100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
int n1 = 10;
int n2 = 20;
int total = addNum(n1, n2);
System.out.println(total);
sayHello("안녕하세요");
total = calcSum();
System.out.println(total);
}
}
Stack 메모리 구조
함수 호출과 스택 메모리
- 스택 : 함수가 호출될 때 지역 변수들이 사용하는 메모리
- 함수의 수행이 끝나면 자동으로 반환되는 메모리
Heap 메모리 구조
- 생성된 인스턴스는 동적 메모리(Heap memory)에 할당됨.
- C나 C++ 언어에서는 사용한 동적 메모릴르 프로그래머가 해제 시켜야 함 (free() 난 delete 이용)
- 자바에서 Garbage Collector가 주기적으로 사용하지 않는 메모리를 수거
- 하나의 클래스로부터 여러개의 인스턴스가 생성되고 각각 다른 메모리 주소를 가지게 됨.
Student.java
public class Student {
public int studentID;
public String studentName;
public String address;
public void showStudentInfo() {
System.out.println( studentID + "학번 학생의 이름은" + studentName + "이고, 주소는 " + address + "입니다.");
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String name) {
studentName = name;
}
}
StudentTest.java
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student();
studentLee.studentID = 12345;
studentLee.setStudentName("Lee");
studentLee.address = "서울 강남구";
studentLee.showStudentInfo();
Student studentKim = new Student();
studentKim.studentID = 54321;
studentKim.studentName = "Kim";
studentKim.address = "경기도 성남시";
studentKim.showStudentInfo();
System.out.println(studentKim); // 참조 값 : 생성된 인스턴스의 메모리 주소 값
System.out.println(studentLee);
// 참조 변수를 가리키는 위치, 즉 메소드 및 함수(스택 영역) - 그 안에 하나의 열로 저장되는 값, 즉 속성 및 멤버변수(힙 영역)
}
}
실행 결과
Author And Source
이 문제에 관하여([Development Record:: JAVA] 2. Stack & Heap Memory), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@yun003318/Development-Record-JAVA-3.-function저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)