[Java] 자료형 (Primitive Type, Reference Type)

Ho·2022년 7월 5일
0

Java

목록 보기
1/1

자바의 자료형

자바의 자료형에는 기본형(primitive type)과 참조형(reference type)이 있다.


1. 기본형 (primitive type)

자바에서 기본적으로 제공하는 자료형
기본형 타입은 변수에 값이 직접 저장되어 스택 영역에 존재한다.

기본 자료형의 종류

자료형크기데이터
boolean1bytetrue, false
char2byte유니코드 문자
byte1byte정수
short2byte정수
int4byte정수
long8byte정수
float4byte실수
double8byte실수

2. 참조형 (reference type)

클래스 자료형을 말한다.
참조형 타입의 변수는 자료형 클래스의 객체가 힙 영역에 생성되고 이를 참조한다.

2-1. 배열(array)

배열로 선언된 변수는 배열의 주소를 참조한다.

int[] intArray = new int[4];

2-2. 클래스(class)

객체를 생성하여 초기화한 변수는 객체의 주소를 참조한다.

public class Student {
	private String name;
    
    Student(String name) {
    	this.name = name;
    }
    
    public void setName() {
    	this.name = name;
    }
    public String getName() {
    	return this.name;
    }
}

Student student1 = new Student("sonny");
System.out.println(student1.getName());

2.3 인터페이스

인터페이스는 추상 메소드와 상수만 있다. 인터페이스 타입은 구현클래스의 객체로 초기화 하여 구현 객체의 주소를 참조한다.

public interface Person {
    void setName(String name);

    String getName();

}
public class Student implements Person{
    private String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }
}
@Test
public void test2() {
    Person person = new Student("sonny");
    System.out.println("person = " + person.getName());
}

이외에 참조형 타입으로는 String, StringBuffer, Wrapper, Collection 등이 있다.

0개의 댓글