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);
}
}
Purpose
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
Byte
class is part of thejava.lang
package, which is automatically imported in Java. - The explicit
import
statement is optional. - The
Byte
wrapper class represents a singlebyte
value and provides utility methods for working withbyte
values.
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
Byte
object by parsing the string argument"55"
into abyte
value. - If the string does not represent a valid
byte
value (i.e., it is not within the range-128
to127
), 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 theByte
class is implicitly called to convert theByte
object into a string for display. - It outputs the value stored in the
Byte
object.
Key Concepts
-
Wrapper Classes:
- Wrapper classes, like
Byte
, allow primitive data types to be used as objects in Java. - The
Byte
class represents the primitivebyte
data 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
byte
values andByte
objects. Example:Byte byObj = 55; // Autoboxing
- Java allows automatic conversion between primitive
-
Range of
byte
:- A
byte
in Java has a range of-128
to127
. Values outside this range will throw an exception.
- A
Output
Value of Byte object : 55
Output
Value of Byte object : 55