How to Initialize a Byte Array in Java?

In this tutorial, we will learn how to initialize a byte array in Java.

What is a byte?

We all know that 8 bits = 1 byte or we can say a combination of eight zeros and ones. A byte represents a sort of digital information or data in binary format.

Byte in Java

A byte in Java is one of the primitive data types. It means, a byte stores the same size as that of computer memory.
If you look at some primitive data types in Java, you will see a byte stores values ranging from -128 to +127. That means we can store the values only from -128 to 127 and if we want some value greater than this range, then we can simply use datatype conversion.

Byte Array in Java

As we have seen, a byte is a combination of eight zeros and ones.
A byte array is a combination of bytes values. It means if you want to load some content directly into the memory then this can be helpful.

How to Initialize a byte array in Java?

Now, there are many ways in which we can initialize a byte array. Examples are given below:

  • byte[] array_name;
public static void main(String[] args){
    // Declaration of byte array
    byte[] myfirstarray = new byte[10];
}
  • byte array_name[];
public static void main(String[] args){
    // Declaration of byte array
    byte myfirstarray[] = new byte[10];
}

When you assign memory to a byte array, initially the default value is zero. This is not only in byte array but also in all the arrays in Java. There is always some initial value allocated to every array.

Assigning Elements to byte array in Java

In Java, we assign elements to the Java array by indexing only.
An example is given below:

public static void main(String[] args){
    // declaration of byte array
    byte[] values = new byte[5];
    
    // Assigning elements
    values[0] = 12;
    values[1] = 10;
    values[2] = 75;
    values[3] = 40;
    values[4] = 101;

    // printing byte elements 
    for(int i=0;i<values.length;i++){
        System.out.println("Element at "+i+": "+values[i]);
    }
}

In this example, you can see, we have declared an array for byte with the size of 5. Then we have assigned values to it with the help of indexing. And printing all values with the help of for-loop iteration.
The output:

Element at 0: 12
Element at 1: 10
Element at 2: 75
Element at 3: 40
Element at 4: 101

Leave a Reply

Your email address will not be published. Required fields are marked *