Java Program to demonstrate Byte wrapper class
Program
import java.lang.Byte;
public class javaLangByteDemo
{
public static void main(String[] args) {
Byte byObj = new Byte("55");
System.out.println("Value of Byte object : " + byObj);
}
}
This program demonstrates how to use the Byte wrapper class, which provides an object representation for the primitive byte data type.
1. Import Statement
import java.lang.Byte;
- The
Byteclass is part of thejava.langpackage, which is automatically imported in Java. - The explicit
importstatement is optional. - The
Bytewrapper class represents a singlebytevalue and provides utility methods for working withbytevalues.
2. Class Definition
public class javaLangByteDemo
- Defines the class
javaLangByteDemo.
3. Main Method
public static void main(String[] args)
- Entry point for the program.
4. Create a Byte Object
Byte byObj = new Byte("55");
- Constructor
Byte(String s):- This constructor creates a
Byteobject by parsing the string argument"55"into abytevalue. - If the string does not represent a valid
bytevalue (i.e., it is not within the range-128to127), it throws aNumberFormatException. - The constructor is deprecated in modern Java versions. Instead, you should use:
Byte byObj = Byte.valueOf("55");
- This constructor creates a
5. Print the Value
System.out.println("Value of Byte object : " + byObj);
- The
toString()method of theByteclass is implicitly called to convert theByteobject into a string for display. - It outputs the value stored in the
Byteobject.
Key Concepts
-
Wrapper Classes:
- Wrapper classes, like
Byte, allow primitive data types to be used as objects in Java. - The
Byteclass represents the primitivebytedata type.
- Wrapper classes, like
-
Deprecated Constructor:
- The
new Byte(String s)constructor is deprecated. UseByte.valueOf(String s)instead.
- The
-
Autoboxing:
- Java allows automatic conversion between primitive
bytevalues andByteobjects. Example:Byte byObj = 55; // Autoboxing
- Java allows automatic conversion between primitive
-
Range of
byte:- A
bytein Java has a range of-128to127. Values outside this range will throw an exception.
- A
Output
Value of Byte object : 55
Output
Value of Byte object : 55