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 the java.lang package, which is automatically imported in Java.
  • The explicit import statement is optional.
  • The Byte wrapper class represents a single byte value and provides utility methods for working with byte 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 a byte value.
    • If the string does not represent a valid byte value (i.e., it is not within the range -128 to 127), it throws a NumberFormatException.
    • The constructor is deprecated in modern Java versions. Instead, you should use:
      Byte byObj = Byte.valueOf("55");
      

5. Print the Value

System.out.println("Value of Byte object : " + byObj);
  • The toString() method of the Byte class is implicitly called to convert the Byte object into a string for display.
  • It outputs the value stored in the Byte object.

Key Concepts

  1. Wrapper Classes:

    • Wrapper classes, like Byte, allow primitive data types to be used as objects in Java.
    • The Byte class represents the primitive byte data type.
  2. Deprecated Constructor:

    • The new Byte(String s) constructor is deprecated. Use Byte.valueOf(String s) instead.
  3. Autoboxing:

    • Java allows automatic conversion between primitive byte values and Byte objects. Example:
      Byte byObj = 55; // Autoboxing
      
  4. Range of byte:

    • A byte in Java has a range of -128 to 127. Values outside this range will throw an exception.

Output

Value of Byte object : 55

Output

Value of Byte object : 55