Byte Data Type in Java: Explanation and Usage

Rumman Ansari   Software Engineer   2024-07-04 03:16:28   12782  Share
Subject Syllabus DetailsSubject Details 1 Questions 1 Program
☰ TContent
☰Fullscreen

Table of Content:

byte

The smallest integer type is byte.The byte data type is an 8-bit signed two’s complement integer.The byte data type is useful for saving memory in large arrays.

Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types.

  • Byte data type is an 8-bit signed two's complement integer

  • Minimum value is -128 (-2^7)

  • Maximum value is 127 (inclusive)(2^7 -1)

  • Default value is 0

  • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.

  • Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called d and k:

     byte d, k;
  • Example:

     byte a = 100, byte b = -50; 

Variable Declaration and Variable Initialization:

Variable Declaration : To declare a variable , you must specify the data type & give the variable a unique name.

 byte age;  

Variable Initialization : To initialize a variable you must assign it a valid value.

 age= 2 ;  

Variable Declaration and Variable Initialization in two steps:

byte age;
age = 20;
byte datatype in java

Example :

Save Source File Name as : ByteExample1.java
To compile : javac ByteExample1.java
To Run : java ByteExample1
// A Java program to demonstrate byte data type
class ByteExample1 {
   public static void main(String args[])
     {
           byte age;
           age = 20;
           System.out.println(age);
     }
  }
Output
20
press any key to continue ...
byte datatype in java

Variable Declaration and Variable Initialization in one line:

byte age = 20;
byte datatype in java

Example :

Save Source File Name as : ByteExample1.java
To compile : javac ByteExample1.java
To Run : java ByteExample1
// A Java program to demonstrate byte data type
class ByteExample1 {
   public static void main(String args[])
     {
           byte age = 20;
           System.out.println(age);
     }
  }
Output
20
press any key to continue ...

Example 2:

// Java program to demonstrate byte data type in Java
class ByteExample2
{
    public static void main(String args[])
    {
        byte a = 126;

        // byte is 8 bit value
        System.out.println(a+"\n");

        a++;
        System.out.println(a+"\n");

        // It overflows here because
        // byte can hold values from -128 to 127
        a++;
        System.out.println(a+"\n");

        // Looping back within the range
        a++;
        System.out.println(a+"\n");
    }
}
126

127

-128

-127

Press any key to continue . . .
MCQ Available

There are 4 MCQs available for this topic.

4 MCQ