Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

int vs Integer #23

Closed
thals0 opened this issue Apr 26, 2023 · 0 comments
Closed

int vs Integer #23

thals0 opened this issue Apr 26, 2023 · 0 comments

Comments

@thals0
Copy link
Owner

thals0 commented Apr 26, 2023

int와 Integer는 모두 정수를 나타내는 자료형이지만, 차이점이 존재합니다.

int : 기본 자료형(primitive data type) 중 하나로, 32비트 크기의 정수를 나타냅니다. int는 값 자체를 나타내기 때문에 null을 가질 수 없으며, 기본값은 0입니다.

Integer : int를 객체로 감싸서 표현한 참조 자료형(reference data type)입니다. Integer는 null 값을 가질 수 있으며, 객체의 메소드를 사용할 수 있습니다. 또한, Integer는 int보다 메모리를 더 많이 사용합니다.

예를 들어, 다음과 같은 코드에서 int와 Integer의 차이를 확인할 수 있습니다.

int x = 10;
Integer y = 20;

System.out.println(x); // 10
System.out.println(y); // 20
System.out.println(y.toString()); // "20"

위 코드에서 int형 변수 x는 그 값 자체를 나타내기 때문에 바로 출력할 수 있습니다. 그러나 Integer형 변수 y는 객체이기 때문에, 출력하기 전에 toString() 메소드를 사용하여 문자열로 변환해야 합니다.

Java에서는 int와 Integer 간에 자동 형변환이 이루어지기 때문에, 두 자료형을 혼용하여 사용할 수 있습니다. 예를 들어, 다음과 같은 코드는 에러 없이 실행됩니다.

int x = 10;
Integer y = 20;

int z = x + y; // 30
Integer w = x + y; // 30

하지만 int와 Integer의 자료형이 다른 상황에서는 형변환을 명시적으로 해줘야 합니다.

@thals0 thals0 closed this as completed May 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant