자바의 Byte 클래스는 기본 타입(primitive type)인 byte 값을 객체로 감싸는 래퍼(wrapper) 클래스입니다. Byte 타입의 객체는 byte 타입의 필드 하나를 포함하고 있으며, 이를 통해 byte 값을 객체로 다룰 수 있습니다.
Byte 클래스에서 자주 사용되는 주요 메서드를 살펴보겠습니다.
Byte 클래스의 주요 메서드
| 번호 | 메서드 및 설명 |
|---|---|
| 1 | byte byteValue()이 Byte 객체의 값을 byte 타입으로 반환합니다. |
| 2 | int compareTo(Byte anotherByte)두 Byte 객체를 수치적으로 비교합니다. |
| 3 | static Byte decode(String nm)문자열을 디코딩하여 Byte 객체로 변환합니다. |
| 4 | double doubleValue()이 Byte 객체의 값을 double 타입으로 반환합니다. |
| 5 | boolean equals(Object obj)이 객체와 지정된 객체를 비교하여 동일 여부를 판단합니다. |
| 6 | float floatValue()이 Byte 객체의 값을 float 타입으로 반환합니다. |
| 7 | int hashCode()이 Byte 객체의 해시 코드(hash code)를 반환합니다. |
| 8 | int intValue()이 Byte 객체의 값을 int 타입으로 반환합니다. |
| 9 | long longValue()이 Byte 객체의 값을 long 타입으로 반환합니다. |
| 10 | static byte parseByte(String s)문자열 인수를 부호 있는 십진수 byte 값으로 파싱(parsing)합니다. |
그럼 실제 예제를 통해 Byte 클래스의 사용법을 확인해 보겠습니다.
예제 1: intValue() 메서드 활용
아래 예제에서는 Byte 객체를 생성한 후, intValue() 메서드를 사용해 int 값으로 변환하는 과정을 보여줍니다.
import java.lang.*;
public class Demo {
public static void main(String[] args){
Byte b1, b2;
int i1, i2;
b1 = new Byte("1");
b2 = new Byte("-1");
i1 = b1.intValue();
i2 = b2.intValue();
String str1 = "int value of Byte " + b1 + " is " + i1;
String str2 = "int value of Byte " + b2 + " is " + i2;
System.out.println( str1 );
System.out.println( str2 );
}
}실행 결과
int value of Byte 1 is 1 int value of Byte -1 is -1
예제 2: toString() 메서드 활용
다음 예제에서는 Byte 객체를 문자열로 변환하는 toString() 메서드의 사용 방법을 살펴봅니다.
import java.lang.*;
public class Demo {
public static void main(String[] args){
Byte b1, b2;
String s1, s2;
b1 = new Byte("-123");
b2 = new Byte("0");
s1 = b1.toString();
s2 = b2.toString();
String str1 = "String value of Byte " + b1 + " is " + s1;
String str2 = "String value of Byte " + b2 + " is " + s2;
System.out.println( str1 );
System.out.println( str2 );
}
}실행 결과
String value of Byte -123 is -123 String value of Byte 0 is 0
위 예제들을 통해 알 수 있듯이, Byte 클래스는 byte 값을 다양한 타입(int, double, float, long 등)으로 손쉽게 변환할 수 있는 유용한 메서드들을 제공합니다. 특히 컬렉션 프레임워크나 제네릭처럼 객체 타입만 허용되는 상황에서 byte 값을 다룰 때 Byte 클래스가 필수적으로 활용됩니다.