Complete Tutorial on Java primitive byte data type array .

Java byte Array

byte Array in Java

Java byte Array is used to store byte data type values only . The default value of the elements in a byte array is 0 .

With the following Java byte array examples you can learn

  • How to declare Java byte array ?
  • How to assign values to Java byte array ?
  • How to get values from Java byte array ?
  • How to convert String to byte array in Java ?
  • How to convert a byte Array to String in Java ?

What is byte ?

A group of binary digits or bits ( usually eight ) operated on as a unit . A byte considered as a unit of memory size .

The byte is a unit of digital information that most commonly consists of eight bits . Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit of memory in many computer architectures .

A byte is a data measurement unit that contains eight bits, or a series of eight zeros and ones . A single byte can be used to represent 28 or 256 different values .

What does byte mean in Java ?

The byte is one of the primitive data types in Java . This means that the Java byte is the same size as a byte in computer memory: it's 8 bits, and can hold values ranging from -128 to 127 . The byte data type comes packaged in the Java programming language and there is nothing special you have to do to get it to work .

What do we mean by byte array ?

A byte is 8 bits (binary data).

A byte array is an array of bytes.

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

How many bits is a byte in Java ?

The byte is equal to 8 bits in Java .

Is byte a keyword in Java ?

The byte is a keyword in Java which designates the 8 bit signed integer primitive type .

The standard Java integer data types are in bytes :

  • byte 1 byte -128 to 127
  • short 2 bytes -32768 to 32767
  • int 4 bytes -2147483648 to 2147483647
  • long 8 bytes -9223372036854775808 to 9223372036854775807

How to declare byte Array in Java ?

Arrays are declared with [] ( square brackets ) . If you put [] ( square brackets ) after any variable of any type only that variable is of type array remaining variables in that declaration are not array variables those are normal variables of that type .

If you put [] ( square brackets ) after any data type all the variables in that declaration are array variables . All the elements in the array are accessed with index . The array element index is starting from 0 to n-1 number i.e. if the array has 5 elements then starting index is 0 and ending index is 4 .

// Java bytearray
// declares an array of bytes
byte[] byteArray;

How to Initialize ( init ) byte Array ( byte[] ) in Java ?

The byte array will be initialized ( init ) to 0 when you allocate it . All arrays in Java are initialized to the default value for the type . This means that arrays of ints are initialized to 0, arrays of booleans are initialized to false and arrays of reference types are initialized to null .

how to init byte array example

// Java bytearray
// how to init byte array or byte[] in java
byte[] byteArray = new byte[10];

What is the Initial or Default Value of a byte Array in Java ?

The initial value of a byte array is 0 . Because the default value of a byte data type in Java is 0 .

What is the length of a byte Array in Java ?

The length is a property of an array object in Java that returns the number of elements in a given array .

What is the Maximum length of a byte Array in Java ?

The maximum length of a byte array in Java is 2147483647 . You can store elements upto 2147483647 .

What is the Length of an Array in Java ?

In Java all the arrays are indexed and declared by int only . That is the size of an array must be specified by an int value and not long or short . All the arrays index beginning from 0 to ends at 2147483646 . You can store elements upto 2147483647 . If you try to store long ( big ) elements in array, you will get performance problems . If you overcome performance problems you should go to java collections framework or simply use Vector .

Syntax :

< data type > < variable >[];
< data type >[] < variable >;

Java byte Array Example

/*  Java byte Array Example
    Save with file name ByteArray.java  */
   
public class ByteArray
{
  public static void main(String args[])
  {
    //JAVA BYTE ARRAY DECLARATION
    byte b[];
    //MEMORY ALLOCATION FOR JAVA BYTE ARRAY
    b = new byte[4];
    //ASSIGNING ELEMENTS TO JAVA BYTE ARRAY
    b[0] = 20;
    b[1] = 10;
    b[2] = 30;
    b[3] = 5;
    //BYTE ARRAY OUTPUT
    System.out.println("Java byte Array Example");
    for(int i=0;i<b.length;i++)
    {
      System.out.println("Element at Index : "+ i + " " + b[i]);
    }
  }
}

Following Java byte array example you can learn how to assign values to java byte array at the time of declaration .

How to assign values to java byte array at the time of declaration

/*  How to assign values to java byte array at the time of declaration Example
    Save with file name ByteArray2.java */
   
public class ByteArray2
{
  public static void main(String args[])
  {
    //JAVA BYTE ARRAY DECLARATION AND ASSIGNMENT
    byte b[] = {20,10,30,5};
    //JAVA BYTE ARRAY OUTPUT
    System.out.println("Java byte Array Example");
    for(int i=0;i<b.length;i++)
    {
      System.out.println("Element at Index : "+ i + " " + b[i]);
    }
  }
}

Following Java byte array example you can learn how to declare Java byte array with other Java byte array variables .

How to declare Java byte array with other Java byte array variables

/*  How to declare Java byte array with other Java byte array variables Example
    Save with file name ByteArray3.java */
   
public class ByteArray3
{
  public static void main(String args[])
  {
    //JAVA BYTE ARRAY DECLARATION
    byte b[], a; //b IS AN ARRAY a IS NOT AN ARRAY
    //MEMORY ALLOCATION FOR JAVA BYTE ARRAY
    b = new byte[4];
    //ASSIGNING ELEMENTS TO JAVA BYTE ARRAY
    b[0] = 20;
    b[1] = 10;
    b[2] = 30;
    b[3] = 5;
    a = 100;
    //JAVA BYTE ARRAY OUTPUT
    System.out.println("Java byte Array Example");
    System.out.println("a value is : "+a);
    for(int i=0;i<b.length;i++)
    {
      System.out.println("Element at Index : "+ i + " " + b[i]);
    }
  }
}

Following Java byte array example you can learn how to assign Java byte array to other Java byte array .

How to assign Java byte array to other Java byte array

/*  How to assign Java byte array to other Java byte array Example
    Save with file name ByteArray4.java */
   
public class ByteArray4
{
  public static void main(String args[])
  {
    //JAVA BYTE ARRAY DECLARATION
    byte[] a, b; //a AND b ARE ARRAY VARIABLES
    //MEMORY ALLOCATION FOR JAVA BYTE ARRAY
    b = new byte[4];
    //ASSIGNING ELEMENTS TO JAVA BYTE ARRAY
    b[0] = 20;
    b[1] = 10;
    b[2] = 30;
    b[3] = 5;
    //ASSIGNING b ARRAY TO a ARRAY VARIABLE
    a = b;
    //JAVA BYTE ARRAY OUTPUT
    System.out.println("Java byte Array Example");
    System.out.println("b array values");
    for(int i=0;i<b.length;i++)
    {
      System.out.println("Element at Index : "+ i + " " + b[i]);
    }
    System.out.println("a array values");
    for(int i=0;i<b.length;i++)
    {
      System.out.println("Element at Index : "+ i + " " + a[i]);
    }
  }
}

Java convert String to byte[]

We can convert String to byte[] in java two ways.

  1. By Using String.getBytes() method
  2. By Using Base64 class in Java 8

How to convert String to byte array in Java ?

To convert from String to byte array , use String.getBytes() method . Please note that this method uses the platform’s default charset .

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform’s default charset . This method is overloaded and we can also pass Charset as argument .

Following program shows how to convert String to byte array in java .

How to convert String to byte array in Java ?

/*  How to convert String to byte array in Java Example
    Save with file name StringToByteArray.java */
  
import java.util.Arrays;
  
// Convert String to byte array in Java
public class StringToByteArray
{
  public static void main(String[] args)
  {
    String str = " convert String to byte Array in Java ";
    byte[] bytearray = str.getBytes();
    System.out.println(Arrays.toString(bytearray));
  }
}

How to convert String to byte array in Java 8 ?

To convert from String to byte array in Java 8, use Base64.getDecoder().decode() method . Base64.getDecoder().decode() method converts a string to byte array . The Base64 class is since java 1.8 so this code won't work before java 1.8 .

Following program shows how to convert String to byte array in java 8 .

How to convert String to byte array in Java 8 ?

/*  How to convert String to byte array in Java 8 Example
    Save with file name StringToByteArrayJava8.java */
import java.util.Arrays;
import java.util.Base64;
  
// Convert String to byte array in Java 8
public class StringToByteArrayJava8
{
  public static void main(String[] args)
  {
    String str = " convert String to byte Array in Java ";
    byte[] bytearray = Base64.getDecoder().decode(str);
    System.out.println(Arrays.toString(bytearray));
  }
}

How to convert a byte Array to String in Java ?

We can convert a byte array to String in java two ways .

  1. Without character encoding.
  2. With character encoding.
  3. By Using Base64 class in Java 8

How to convert a byte Array to String in Java without character encoding ?

We can convert the byte array to String without even specifying the character encoding . Just pass the byte array to the String constructor .

How to convert a byte Array to String in Java without character encoding ?

/*  How to convert a byte Array to String in Java
    without character encoding Example
    Save with file name ByteArrayToString.java */
import java.io.IOException;
import java.util.Arrays;
  
// Convert a byte array to String in Java
public class ByteArrayToString
{
  public static void main(String[] args) throws IOException
  {
  
    byte[] bytes = " convert a byte Array to String in Java without character encoding ".getBytes();
     System.out.println(Arrays.toString(bytes));
  
    // Create a string from the byte array
    // without specifying character encoding
    String string = new String(bytes);
    System.out.println(string);
  }
}

How to convert a byte Array to String in Java with character encoding ?

We can convert the byte array to String with UTF-8 character encoding .

How to convert a byte Array to String in Java with character encoding ?

/*  How to convert a byte Array to String in Java
    with character encoding Example
    Save with file name ByteArrayToString2.java */
import java.io.IOException;
import java.nio.charset.StandardCharsets;
  
// Convert a byte array to String in Java
class ByteArrayToString2
{
  public static void main(String[] args) throws IOException
  {
    byte[] bytes = " convert a byte Array to String in Java with UTF-8 character encoding ".getBytes(StandardCharsets.UTF_8);
  
    // Create a string from the byte array with "UTF-8" encoding
    String str = new String(bytes, StandardCharsets.UTF_8);
    System.out.println(str);
  }
}

How to convert byte array to String in Java 8 ?

To convert from byte array to String in Java 8, use Base64.getEncoder().encodeToString() method . Base64.getEncoder().encodeToString() method converts byte array to String . The Base64 class is since java 1.8 so this code won't work before java 1.8 .

Following program shows how to convert byte array to String in java 8 .

How to convert byte array to String in Java 8 ?

/*  How to convert byte array to String in Java 8 Example
    Save with file name ByteArrayToStringJava8.java */
import java.util.Arrays;
import java.util.Base64;
  
// Convert byte array String in Java 8
public class ByteArrayToStringJava8
{
  public static void main(String[] args)
  {
      
    byte[] bytearray = " convert byte Array to String in Java 8 ".getBytes();
    String str = Base64.getEncoder().encodeToString(bytearray);
    System.out.println(str);
  }
}

What is ByteBuffer in Java ?

A byte buffer is either direct or non-direct . Given a direct byte buffer , the Java virtual machine will make a best effort to perform native I/O operations directly upon it . That is , it will attempt to avoid copying the buffer's content to ( or from ) an intermediate buffer before ( or after ) each invocation of one of the underlying operating system's native I/O operations .

The allocate() method of java.nio.ByteBuffer class is used to allocate a new byte buffer .

The new buffer's position will be zero , its limit will be its capacity , its mark will be undefined , and each of its elements will be initialized to zero . It will have a backing array , and its array offset will be zero .

How to convert Java integer to byte Array ?

We will discuss various ways of converting int to a byte array . In java int data type take 4 bytes ( 32 bits ) and it’s range is -2147483648 to 2147483647 .

You can convert Java integer to byte Array using Java NIO's ByteBuffer is very simple . Following example shows how to convert Java integer to byte Array .

How to convert Java integer to byte Array ?

/*  How to convert Java integer to byte Array Example
    Save with file name IntToByteArray.java */
import java.nio.ByteBuffer;
  
// Convert integer to byte array
public class IntToByteArray
{
  public static void main(String[] args)
  {
    byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
  
    for (byte b : bytes)
    {
      System.out.format("0x%x ", b);
    }
  }
}

How to convert Java byte Array to long ?

Java provide ByteBuffer class to do the same . To convert any byte array , first we need to allocate 8 bytes using ByteBuffer's static method allocate , then put byteArray using put method and flip bytebuffer by calling getLong() method we can get long value of that byte array .

You can convert Java byte Array to long using Java NIO's ByteBuffer is very simple .

How to convert Java byte Array to long ?

/*  How to convert Java byte Array to long Example
    Save with file name ByteArrayToLong.java */
import java.nio.ByteBuffer;
  
// Convert byte array to long
public class ByteArrayToLong
{
  public static void main(String[] args)
  {
    byte [] bytes = { 0, 6, 36, -84, 113, 125, -118, -47 };
    System.out.println(ByteBuffer.wrap(bytes).getLong());
    System.out.println(convertByteArrayToLong(bytes));
  }
  public static long convertByteArrayToLong(byte[] longBytes)
  {
    ByteBuffer byteBuffer = ByteBuffer.allocate(Long.BYTES);
    byteBuffer.put(longBytes);
    byteBuffer.flip();
    return byteBuffer.getLong();
  }
}

How to convert an object to byte array in Java ?

  1. Make the required object serializable by implementing the Serializable interface .
  2. Create a ByteArrayOutputStream object .
  3. Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step .
  4. Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class .
  5. Flush the contents to the stream using the flush() method .
  6. Finally , convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method .

Following example shows how to convert an object to byte array . Prepare the byte array to send:

How to convert an object to byte array in Java ?

/*  How to convert an object to byte array Example
    Save with file name ObjectToByteArray.java */
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.IOException;
  
// Convert an object to byte array
public class ObjectToByteArray
{
  public static void main(String[] args)
  {
    Sample yourObject = null;
    ByteArrayOutputStream bos = null;
    ObjectOutputStream out = null;
    try
    {
      yourObject = new Sample();
      bos = new ByteArrayOutputStream();
      out = new ObjectOutputStream(bos);
      out.writeObject(yourObject);
      out.flush();
      byte[] yourBytes = bos.toByteArray();
    }
    catch(Exception e)
    {
      // handle exception here.
    }
    finally
    {
      try
      {
        bos.close();
      } catch (IOException ex)
      {
        // ignore close exception
      }
    }
  }
}
  
class Sample implements Serializable
{
  public void display()
  {
    System.out.println("This is a sample class");
  }
}

How to Convert byte[] ( array ) to File using Java ?

"hello".getBytes(); encodes given String into a sequence of bytes using the platform's default charset , Which stores the result into a new byte array .

new File("c:\\demo.txt") Creates a new File instance by converting the given pathname string into an abstract pathname .

new FileOutputStream(file) Creates a file output stream to write to the file represented by the specified File object .

os.write(bytes) Writes number of bytes from the specified byte array to output stream .

Following example shows how to Convert byte[] ( Array ) to File .

How to Convert byte[] ( array ) to File using Java ?

/*  How to convert byte array to File Example
    Save with file name ByteArrayToFile.java */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
  
// Convert byte array to File
public class ByteArrayToFile
{
  public static void main(String[] args)
  {
    byte[] bytes = "hello".getBytes();
    File file = new File("c:\\demo.txt");
    try
    {
      OutputStream os = new FileOutputStream(file);
      os.write(bytes);
      System.out.println("Write bytes to file.");
      printContent(file);
      os.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  public static void printContent(File file) throws Exception
  {
    System.out.println("Print File Content");
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = null;
    while ((line = br.readLine()) != null)
    {
      System.out.println(line);
    }
    br.close();
  }
}

Java Byte Array More Related Articles

Java long Array


Java long array is used to store long data type values only in Java. The default value of the elements in a Java long array is 0. Java long array variable can also be declared like other variables with [] after the data type. Learn more about Java long Array

Java Arrays


An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Learn more about Java Arrays