1. 기본형의 한계
- 객체가 아님: 기본형 데이터는 객체가 아니기 때문에, 객체 지향 프로그래밍의 장점을 살릴 수 없다. 예를 들어 객
체는 유용한 메서드를 제공할 수 있는데, 기본형은 객체가 아니므로 메서드를 제공할 수 없다.
추가로 객체 참조가 필요한 컬렉션 프레임워크를 사용할 수 없다. 그리고 제네릭도 사용할 수 없다. - null 값을 가질 수 없음: 기본형 데이터 타입은 null 값을 가질 수 없다. 때로는 데이터가 없음 이라는 상태를 나
타내야 할 필요가 있는데, 기본형은 항상 값을 가지기 때문에 이런 표현을 할 수 없다.
2. 자바 래퍼 클래스
- byte -> Byte
- short -> Short
- int -> Integer
- long -> Long
- float -> Float
- double -> Double
- char -> Character
- boolean -> Boolean
- 래퍼클래스는 불변 객체이다.
- equals로 비교해야 한다. -> 기본형이 아니라 참조값을 가지고 있기 때문이다.
- 래퍼 클래스 생성 - 박싱(Boxing)
- 기본형을 래퍼 클래스로 변경하는 것을 마치 박스에 물건을 넣은 것 같다고 해서 박싱(Boxing)이라 한다.
- Integer.valueOf() 메서드를 사용
- 래퍼 클래스 생성 - 언박싱(UnBoxing)
- 래퍼 클래스에 들어있는 기본형 값을 다시 꺼내는 메서드이다.
- 박스에 들어있는 물건을 꺼내는 것 같다고 해서 언박싱(Unboxing)이라 한다
3. 래퍼 클래스 - Auto Boxing
- 다음 코드는 오토 박싱 방법을 사용하지 않고 박싱과 언박싱을 구현한 코드이다.
package lang.wrapper;
public class AutoboxingMain1 {
// Primitive -> Wrapper
public static void main(String[] args) {
int value = 7;
Integer boxedValue = Integer.valueOf(value);
System.out.println("boxedValue = " + boxedValue);
// Wrapper -> Primitive
int unboxedValue = boxedValue.intValue();
System.out.println("unboxedValue = " + unboxedValue);
}
}
오토박싱 사용
package lang.wrapper;
public class AutoboxingMain2 {
// Primitive -> Wrapper
public static void main(String[] args) {
int value = 7;
Integer boxedValue = value; // 오토박싱
System.out.println("boxedValue = " + boxedValue);
// Wrapper -> Primitive
int unboxedValue = boxedValue;
System.out.println("unboxedValue = " + unboxedValue);
}
}
- 오토 박싱과 오토 언박싱은 컴파일러가 개발자 대신 valueOf , xxxValue() 등의 코드를 추가해주는 기능이다
4. 래퍼클래스 - 주요 메서드와 성능
주요 메서드
package lang.wrapper;
public class WrapperUtilsMain {
public static void main(String[] args) {
Integer i1 = Integer.valueOf(10); // 숫자, 래퍼 객체 반환
System.out.println("i1 = " + i1);
Integer i2 = Integer.valueOf("10"); // 문자열, 래퍼 객체 반환
System.out.println("i2 = " + i2);
int i3 = Integer.parseInt("10", 2); // 문자열 전용, 기본형 반환
System.out.println("i3 = " + i3);
int i = i1.compareTo(20);
System.out.println("i = " + i);
System.out.println("sum = " + Integer.sum(i1, i2));
}
}
실행 결과
C:\Users\SAMSUNG\.jdks\jbrsdk-17.0.9\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2023.2.1\lib\idea_rt.jar=60226:C:\Program Files\JetBrains\IntelliJ IDEA 2023.2.1\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\SAMSUNG\Desktop\인프런\java-mid1\out\production\java-mid1 lang.wrapper.WrapperUtilsMain
i1 = 10
i2 = 10
i3 = 2
i = -1
sum = 20
- valueOf() : 래퍼 타입을 반환한다. 숫자, 문자열을 모두 지원한다.
- parseInt() : 문자열을 기본형으로 변환한다.
- compareTo() : 내 값과 인수로 넘어온 값을 비교한다. 내 값이 크면 1 , 같으면 0 , 내 값이 작으면 -1 을 반환
한다. - Integer.sum() , Integer.min() , Integer.max() : static 메서드이다. 간단한 덧셈, 작은 값, 큰
값 연산을 수행한다. - parseInt() vs valueOf()
- 원하는 타입에 맞는 메서드를 사용하면 된다.
- valueOf("10") 는 래퍼 타입을 반환한다.
- parseInt("10") 는 기본형을 반환한다.
- Long.parseLong() 처럼 각 타입에 parseXxx() 가 존재한다
5. Class 클래스
** 자바에서 Class 클래스는 클래스의 정보(메타 데이터)를 다루는 데 사용된다.
주요기능
- 타입 정보 얻기: 클래스의 이름, 슈퍼클래스, 인터페이스, 접근 제한자 등과 같은 정보를 조회할 수 있다.
- 리플렉션: 클래스에 정의된 메서드, 필드, 생성자 등을 조회하고, 이들을 통해 객체 인스턴스를 생성하거나 메서드
를 호출하는 등의 작업을 할 수 있다. - 동적 로딩과 생성: Class.forName() 메서드를 사용하여 클래스를 동적으로 로드하고, newInstance()
메서드를 통해 새로운 인스턴스를 생성할 수 있다. - 애노테이션 처리: 클래스에 적용된 애노테이션(annotation)을 조회하고 처리하는 기능을 제공한다.
- 메서드
- getDeclaredFields(): 클래스의 모든 필드를 조회한다.
- getDeclaredMethods(): 클래스의 모든 메서드를 조회한다.
- getSuperclass(): 클래스의 부모 클래스를 조회한다.
- getInterfaces(): 클래스의 인터페이스들을 조회한다.
예제 코드
package lang.clazz;
public class ClassCreateMain {
public static void main(String[] args) throws Exception {
//Class helloClass = Hello.class;
Class helloClass = Class.forName("lang.clazz.Hello");
Hello hello = (Hello) helloClass.getDeclaredConstructor().newInstance();
String result = hello.hello();
System.out.println("result = " + result);
}
}
- getDeclaredConstructor().newInstance()
- getDeclaredConstructor() : 생성자를 선택한다.
- newInstance() : 선택된 생성자를 기반으로 인스턴스를 생성한다.
6. System 클래스
package lang.wrapper.system;
import java.util.Arrays;
import java.util.Map;
public class SystemMain {
public static void main(String[] args) {
long currentTimeMillis = System.currentTimeMillis();
System.out.println("currentTimeMillis = " + currentTimeMillis);
// 현재 시간(나노초)
long currentNano = System.nanoTime();
// 환경 변수를 읽는다;
Map<String, String> getenv = System.getenv();
System.out.println("getenv = " + getenv);
// 시스템 속성을 읽는다
System.out.println("properties = " + System.getProperties());
System.out.println("Java Version = " + System.getProperty("java.version"));
// 배열을 고속으로 복사
char[] chars = {'h', 'e', 'l', 'l', 'o'};
char[] copiedArr = new char[5];
System.arraycopy(chars, 0, copiedArr,0, chars.length);
// 배열 출력
System.out.println("copiedArr = " + copiedArr);
System.out.println("copiedArr = " + Arrays.toString(copiedArr));
// 프로그램 종료
System.exit(0);
System.out.println("hello");
}
}
- 표준 입력, 출력, 오류 스트림: System.in , System.out , System.err 은 각각 표준 입력, 표준 출력, 표준
오류 스트림을 나타낸다. - 시간 측정: System.currentTimeMillis() 와 System.nanoTime() 은 현재 시간을 밀리초 또는 나노초
단위로 제공한다. - 환경 변수: System.getenv() 메서드를 사용하여 OS에서 설정한 환경 변수의 값을 얻을 수 있다.
- 시스템 속성: System.getProperties() 를 사용해 현재 시스템 속성을 얻거나
System.getProperty(String key) 로 특정 속성을 얻을 수 있다. 시스템 속성은 자바에서 사용하는 설정
값이다. - 시스템 종료: System.exit(int status) 메서드는 프로그램을 종료하고, OS에 프로그램 종료의 상태 코
드를 전달한다. - 상태 코드 0 : 정상 종료
- 상태 코드 0 이 아님: 오류나 예외적인 종료
- 배열 고속 복사: System.arraycopy 는 시스템 레벨에서 최적화된 메모리 복사 연산을 사용한다. 직접 반복문
을 사용해서 배열을 복사할 때 보다 수 배 이상 빠른 성능을 제공한다.
7. Random 클래스
package lang.wrapper.amth;
import java.util.Random;
public class RandomMain {
public static void main(String[] args) {
Random random = new Random(1); // Seed가 같으면 Random의 결과가 같다
int randomInt = random.nextInt();
System.out.println("randomInt = " + randomInt);
double randomDouble = random.nextDouble(); // 0.0d ~ 1.0d
System.out.println("randomDouble = " + randomDouble);
boolean randomBoolean = random.nextBoolean();
System.out.println("randomBoolean = " + randomBoolean);
// 범위 조회
int randomChoiceInt = random.nextInt(9999);
System.out.println(randomChoiceInt);
int randomRange2 = random.nextInt(10) + 1; // 1 ~ 10까지 랜덤으로 출력
System.out.println("randomRange2 = " + randomRange2);
}
}
- random.nextInt() : 랜덤 int 값을 반환한다.
- nextDouble() : 0.0d ~ 1.0d 사이의 랜덤 double 값을 반환한다.
- nextBoolean() : 랜덤 boolean 값을 반환한다.
- nextInt(int bound) : 0 ~ bound 미만의 숫자를 랜덤으로 반환한다. 예를 들어서 3을 입력하면 0, 1,
2 를 반환한다.
출처 : 인프런 김영한 자바 중급 1편
'Java' 카테고리의 다른 글
| Java 중급 1 - 날짜와 시간(1) (0) | 2025.03.16 |
|---|---|
| Java 중급 1 - 열거형 Enum (0) | 2025.02.24 |
| Java 중급 1 - String (0) | 2025.02.14 |
| Java 중급 1 - 불변객체 (0) | 2025.02.14 |
| JAVA 중급 1 - Object 클래스 (0) | 2025.02.14 |