기본형 vs 참조형

한라봉봉·2023년 12월 15일

JAVA

목록 보기
3/16

개념

  1. 기본형(Primitive Type) : int, long, double, boolean처럼 변수에 사용할 값을 직접 넣을수있는 데이터 타입
  2. 참조형(Reference Type) : Student student1, int[] students와 같이 데이터에 접근하기위한 참조 주소를 저장하는 데이터 타입. 참조형은 객체 또는 배열에 사용

접근

  1. 기본형은 숫자 10, 20과 같이 해당값을 바로 사용할수 있다.
  2. 참조형은 메모리로 찾아가야 사용할 수 있다.
    • 객체는 . 을 통해서/ 배열은 [] 를 통해서

계산

  1. 기본형은 들어있는값 그대로 계산
int a =10, b= 20;
int sum = a + b;
  1. 참조형은 주소값만으로는 계산불가. 객체의 기본형 멤버 변수에 접근한 경우에는 연산을 할수있다.
Student s1 = new Student();
Student s2 = new Student();
s1+s2 //오류 발생

s1.grade = 100;
s2.grade = 90;
int sum = s1.grade + s2.grade //연산가능

쉽게 이해하는 팁

기본형을 제외한 나머지는 모두 참조형이다.
1. 기본형은 소문자로 시작한다. int, long, double, boolean 모두 소문자로시작.

  • 기본형은 개발자가 새로 정의할 수없다.
  1. 클래스는 대문자로 시작한다.
  • 클래스는 모두 참조형이다.

참고 - String

String은 클래스이나 기본형처럼 문자값을 바로 대입가능. 자주사용되므로 자바에서 편의 기능을 제공하는것

변수대입

기본형, 참조형 모두 변수에 있는 값을 복사해서 대입한다.
기본형은 해당 값을 복사해서 대입하므로 2개이다.
참조형은 객체의 위치를 가르키는 참조만 복사해 대입한다. 메모리에서는 하나이다.

  1. 기본형은 b변수에 대입후 변경시 기존 a변수 값에 아무런 영향이 없다.
  2. 참조형은 b변수에 대입후 변경시 기존 a값를 참조해서 확인하면 값이 변경되어 있다.

기본형과 메서드 호출

  • 기본형은 대입시 기존 변수값에 영향이 없다.
public class Main {
  public static void main(String[] args) {

    int a = 10;
    System.out.println(a);//10
    
    changePrimitive(a);
    System.out.println(a); //10
    

  }
  static void changePrimitive(int x){
    x = 20;
  }
}

참조형과 메서드 호출

  • 참조형은 대입시 기존 변수도 영향받는다.
public class Main {
  public static void main(String[] args) {

    Data dataA = new Data();
    dataA.value = 10;
    System.out.println(dataA.value); //10

    changeReference(dataA);
    System.out.println(dataA.value); //20
  }
  static void changeReference(Data dataX){
    dataX.value = 20;
  }
}

활용

참조형인 Student 인스턴스에 접근해 값을 바꾸면 실제 메모리가 변경된다.
이를 이용해 메소드를 만들어 코드의 중복을 제거한다.
참조값을 반환하기 때문에 해당 주소값(student1에 저장됨)만 있으면 외부에서 메모리에 접근가능하다.

public class Main {
  public static void main(String[] args) {
    Student student1 = createStudent("학생1", 15, 90);
    Student student2 = createStudent("학생2", 16, 80);

    printStudent(student1);
    printStudent(student2);


  }
  static Student createStudent(String name, int age, int grade){
    Student student = new Student();
    student.name = name;
    student.age = age;
    student.grade = grade;
    return student; // 참조값반환
  }

  static void printStudent(Student student){
      System.out.println("이름: "+student.name + " 나이:"+ student.age + " 성적:"+ student.grade);
  }
}
profile
백엔드 개발공부 로그를 기록합니다

0개의 댓글