Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 백준 16927
- 프로그래머스 옹알이 java
- 프로그래머스 연속된 수의 합 java
- 백준 15661
- 자바
- Arrays
- 프로그래머스 도둑질 java
- 코딩테스트
- java
- 0으로 채우기
- 알고리즘
- 네트워크
- java 내림
- Codility
- java 올림
- 백준 14391
- java 반올림
- 백준 4375
- 백준 11723
- Algorithm
- Math.floor()
- 백준 18290
- 프로그래머스 네트워크 java
- sort
- mysql
- 백준 16935
- Math.ceil()
- 백준 17425
- 프로그래머스 숫자의 표현 java
- time complexity
Archives
- Today
- Total
취미처럼
[JAVA] boxing, unboxing 본문
자바에는 int, double, float와 같은 기본형(primitive type)의 자료형과 포장 클래스(wrapper)가 있다.
wrapper class
1. 객체 또는 클래스가 제공하는 메서드 또는 생성자에 필요(기본형이 아닌 객체로 저장이 되어야 할 때)
Collection을 예로 들 수 있다.
Map에는 Key와 Value가 있다. 선언을 할 때 Map에는 Key와 Value를 참조형만 받을 수 있다. 그래서 Map<String, Integer>으로 선언을 한다. Map<String, int>는 성립되지 않는다.
2. 클래스가 제공하는 상수 사용(MIN_VALUE and MAX_VALUE)
3. 숫자, 문자로의 형 변환 또는 진법 변환에 사용
Integer.parseInt를 예를 들 수 있다.
기본형 객체를 Wrapper 로 바꿔주는 것을 박싱이라고 하고 반대로 Wrapper 클래스 타입의 값을 Primitive로 바꾸는 것을 언박싱이라고 한다.
public static void main(String[] args) {
int intData = 100;
//박싱(boxing)
Integer integerData = new Integer(intData);
System.out.println(integerData);
//언박싱(unboxing)
int intData2 = integerData.intValue();
System.out.println(intData2);
System.out.println(intData == integerData); //true
System.out.println(intData == intData2); //true
}
명시적 묵시적인 박싱과 언박싱
1. 묵시적인 박싱
묵시적인 박싱이랑 프로그래머가 임의로 박싱을 해주는 것이 아니라 자동으로 박싱이 되는 것을 말한다.
2. 묵시적인 언박싱
코드상 프로그래머가 임의로 언박싱을 하는 것이 아니라 자동으로 언박싱이 되는 현상을 말한다.
public static void main(String[] args) {
int intData = 100;
// 묵시적인 방식
Integer integerData = intData;
System.out.println(integerData);
// 묵시적인 언방식
int sum = integerData + 100;
System.out.println(sum);
}
1. 명시적인 박싱
프로그래머가 코딩하여 명시적으로 wrapper로 변환하는 것
2. 명시적인 언박싱
프로그래머가 코딩하여 명시적으로 primitive로 변환하는 것
public static void main(String[] args) {
int intData = 100;
// 명시적인 방식
Integer integerData = (Integer)intData;
System.out.println(integerData);
// 명시적인 언방식
int sum = (int)integerData + 100;
System.out.println(sum);
}
'JAVA > 이론' 카테고리의 다른 글
[JAVA] 콜백 (0) | 2021.03.23 |
---|---|
[JAVA] 참조 (0) | 2021.03.23 |
[JAVA] Map 출력 (0) | 2021.03.22 |
[JAVA] @SuppressWarnings (0) | 2021.03.22 |
[JAVA] 객체 비교 (0) | 2021.03.22 |
Comments