프로그래밍/Java

[자바 문법] 기본형 vs 참조형

코드몬스터 2022. 9. 26. 16:48
728x90
💡 본 내용은 코드잇의 자바 객체지향 프로그래밍을 듣고 정리한 내용입니다.

 

자바의 변수에는 두 가지 종류가 있다.

 

하나는 기본형(Primitive Type)참조형(Reference Type) 이다.

 

기본형(Primitive Type)

  • 변수가 값 자체를 보관
  • 1bit  = 2진수 1자리 / 1byte  = 8bit
  • 논리형(1byte)
    • true, false
  • 문자형
    • Char(2byte) 
  • 정수형
    • byte(1byte), short(2byte), int(4byte), long(8byte)
  • 실수형
    • float(4byte), double(8byte)
int a = 3;
int b = a;

System.out.println(a); 	// 3 출력
System.out.println(b);  // 4 출력


a = 4;
System.out.println(a);	// 4 출력
System.out.println(b);  // 3 출력


b = 7
System.out.println(a);	// 4 출력
System.out.println(b);  // 7 출력

 

 

참조형(Reference Type)

  • 변수는 값이 보관되어 있는 영역을 가리킴
  • Person,String, int[] 등 클래스 기반 자료형은 모두 참조형

Person p1, p2;
p1 = new Person("김신의",28);
p2 = p1;

p2.setName("문종모");

System.out.println(p1.getName());	// 문종모 출력
System.out.println(p2.getName());	// 문종모 출력



// 배열

int[] a = new int[3];
int[] b = a;

a[0] = 1;
b[0] = 2;

System.out.println(a[0]);	// 2 출력
System.out.println(b[0]);	// 2 출력

 

👉 null

  • 자바에서는 "비어있음"을 null 로 값을 표현한다.
  • 단, null 은 참조형 변수(Reference Type)만 가질 수 있다.
  • 만약, null을 보관하고 있는 변수의 메소드를 호출하면 NullPointerException 이라는 오류가 발생
Person[] people = new Person[5];
people[0] = new Person("김신의", 28);
people[2] = new Person("문종모", 26);
people[3] = new Person("서혜린", 21);

for (int i = 0; i < people.length; i++) {
    Person p = people[i];
    if (p != null) {
        System.out.println(p.getName());
    } else {
        System.out.println(i + "번 자리는 비었습니다.");
    }
}


/*
김신의
1번 자리는 비었습니다.
문종모
서혜린
4번 자리는 비었습니다.
*/