Java byte Array - byte Array in Java, initialize, String
Java byte Array
byte Array in Java
byte Array
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 byte array in Java ?
- How to initialize byte array in Java ?
- How to initialize empty byte array in Java ?
- How to assign value to byte array in Java ?
- 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 ?
- How to convert Java byte array to String ?
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 ( byte[] ), 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
What is byte array ?
The byte array is an array of bytes.
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 .
// How to declare byte array in Java Example
byte[] byteArray;
byte byteArray[];
byte[] byte_array;
byte[] java_byte_array;
Related : Java boolean Array
Initializing byte Array
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];
How to initialize empty byte array in Java ?
You can initialize empty byte array in Java following ways.
// How to initialize empty byte array in Java Example
byte[] empty_byte_array = new byte[5];
How to Check byte Array is null in Java ?
int array[] = null; if(array == null) { System.out.println("Array is null"); }
Empty Check Array Null Using Java 8. If you are working with Java 8 or higher version then you can use the stream() method of Arrays class to call the allMatch() method to check whether array contains null values or not. This example is also useful for How to validate byte array in Java ?
How to Check byte Array Size in Java ?
In Java byte is occupied in memory is 1 byte. The size of byte array is equal to the length of byte array.
Java byte Array Size Example
public class ByteArraySize { public static void main(String args[]) { String str = "byte array size example"; byte array[] = str.getBytes(); System.out.println("Size of byte Array : "+array.length); } }
Related : Java char Array
How to Check Empty byte Array in Java ?
To check byte array is empty or not, check all the elements in a byte array are zeros. If all the elements in a byte array are zeros then it is an empty byte array.
Java byte Array is Empty or not Example
public class EmptyByteArray { public static void main(String args[]) { boolean empty_byte_array = true; byte[] byte_array = new byte[10]; for (byte b : byte_array) { if(b != 0) { empty_byte_array = false; break; } } if(empty_byte_array) System.out.println("byte Array is Empty"); else System.out.println("byte Array is not Empty"); } }
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 >;
Following program shows Java byte Array Example . Save the following Java byte Array Example program with file name JavaByteArray.java .
Java byte Array Example
public class JavaByteArray { 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; System.out.println("Java byte Array Example"); for(int i=0;i<b.length;i++) { System.out.println("Element at Index : "+ i + " " + b[i]); } } }
Related : Java short Array
Assigning Values to byte Array
How to assign value to byte array in Java ?
Following Java byte array example you can learn how to assign values to java byte array at the time of declaration . Following example shows How to assign values to java byte array at the time of declaration . Save the following assign values to java byte array at the time of declaration Example program with file name AssignValuesToByteArray.java .
How to assign values to java byte array at the time of declaration
public class AssignValuesToByteArray { public static void main(String args[]) { //JAVA BYTE ARRAY DECLARATION AND ASSIGNMENT byte b[] = {20,10,30,5}; for(int i=0;i<b.length;i++) { System.out.println("Element at Index : "+ i + " " + b[i]); } } }
How to declare Java byte array with other Java byte array variables ?
Following Java byte array example you can learn how to declare Java byte array with other Java byte array variables . Following example shows How to declare Java byte array with other Java byte array variables . Save the following declare Java byte array with other Java byte array variables Example program with file name DeclareMultipleByteArrays.java .
Declare Java byte array with other Java byte array variables Example
public class DeclareMultipleByteArrays { public static void main(String args[]) { // JAVA BYTE ARRAY DECLARATION byte b[], a; // b IS AN ARRAY a IS NOT AN 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("a value is : "+a); for(int i=0;i<b.length;i++) { System.out.println("Element at Index : "+ i + " " + b[i]); } } }
Related : Java int Array
How to assign Java byte array to other Java byte array ?
Following Java byte array example you can learn how to assign Java byte array to other Java byte array . Following example shows How to assign Java byte array to other Java byte array . Save the following assign Java byte array to other Java byte array Example program with file name AssignByteArrayToByteArray.java .
Assign Java byte array to other Java byte array Example
public class AssignByteArrayToByteArray { public static void main(String args[]) { byte[] a, b; b = new byte[4]; b[0] = 20; b[1] = 10; b[2] = 30; b[3] = 5; // ASSIGNING b ARRAY TO a ARRAY VARIABLE a = b; 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]); } } }
Related : Java float Array
Converting to byte Array
Java convert String to byte[]
We can convert String to byte[] in java two ways.
- By Using String.getBytes() method
- 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 example shows How to convert String to byte array in Java . Save the following convert String to byte array in Java Example program with file name StringToByteArray.java .
Convert String to byte array in Java Example
import java.util.Arrays; 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)); } }
Related : Java long Array
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 example shows How to convert String to byte array in Java 8 . Save the following convert String to byte array in Java 8 Example program with file name StringToByteArrayJava8.java . Please note in the ByteArrayToFile.java program the import statement import java.util.* is used, in detail the import statements java.util.Arrays, java.util.Base64 used.
Convert String to byte array in Java 8 Example
import java.util.*; 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)); } }
Related Topic Java Byte Array to SQL Server : How to store byte array in SQL Server using Java ?
How to convert byte[] array to String in Java ?
In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String. For text or character data, we use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset.
We can convert Java byte array to String in two ways .
- Without character encoding.
- With character encoding.
- 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 .
Following example shows How to convert a byte Array to String in Java without character encoding . Save the following convert a byte Array to String in Java without character encoding Example program with file name ByteArrayToString.java .
Convert a byte Array to String in Java without character encoding Example
import java.io.IOException; import java.util.Arrays; 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 .
Following example shows How to convert a byte Array to String in Java with character encoding . Save the following convert a byte Array to String in Java with character encoding Example program with file name ByteArrayToString2.java .
Convert a byte Array to String in Java with character encoding Example
import java.io.IOException; import java.nio.charset.StandardCharsets; 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); } }
Related : Java double Array
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 example shows How to convert byte array to String in Java 8 . Save the following convert byte array to String in Java 8 Example program with file name ByteArrayToStringJava8.java . Please note in the ByteArrayToFile.java program the import statement import java.util.* is used, in detail the import statements java.util.Arrays, java.util.Base64 used.
Convert byte array to String in Java 8 Example
import java.util.*; 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); } }
Related Topic Java Byte Array to MySQL : How to store byte array in MySQL using Java ?
How to convert byte array to base64 String in Java 6 ?
To convert from byte array to base64 String in Java 6, use javax.xml.bind.DatatypeConverter class.
Following example shows How to convert byte array to base64 String in Java 6 . Save the following convert byte array to base64 String in Java 6 Example program with file name ByteArrayToBase64String.java .
Convert byte array to base64 String in Java 6 Example
/* JAXB-API needed to run ByteArrayToBase64String.java */ import javax.xml.bind.DatatypeConverter; public class ByteArrayToBase64String { public static void main(String args[]) { String byte_array_data = "This is byte Array to base64 String Example in Java 6"; byte[] byte_array = byte_array_data.getBytes(); String base64 = DatatypeConverter.printBase64Binary(byte_array); System.out.println(base64); } }
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 .
Following example shows How to convert Java integer to byte Array . Save the following convert Java integer to byte Array Example program with file name IntToByteArray.java .
Convert Java integer to byte Array Example
import java.nio.ByteBuffer; 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 .
Following example shows How to convert Java byte Array to long . Save the following convert Java byte Array to long program with file name ByteArrayToLong.java .
Convert Java byte Array to long Example
import java.nio.ByteBuffer; 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 ?
- Make the required object serializable by implementing the Serializable interface .
- Create a ByteArrayOutputStream object .
- Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step .
- Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class .
- Flush the contents to the stream using the flush() method .
- 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 in Java . Save the following convert an object to byte array program with file name ObjectToByteArray.java . Please note in the ObjectToByteArray.java program the import statement import java.io.* is used in detail, the import statements import java.io.ByteArrayOutputStream, import java.io.ObjectOutputStream, import java.io.Serializable, import java.io.IOException used.
Convert an object to byte array in Java Example
import java.io.*; 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) { System.out.println("Exception"); } finally { try { bos.close(); } catch (IOException ex) { System.out.println("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 ?
- To convert byte[] to file getBytes() method of String class is used, and simple write() method can be used to convert that byte into a file.
- "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 Example . Save the following convert Java byte array to File program with file name ByteArrayToFile.java . Please note in the ByteArrayToFile.java program the import statement import java.io.* is used in detail, the import statements import java.io.BufferedReader, import java.io.File, import java.io.FileOutputStream, import java.io.FileReader, import java.io.OutputStream used.
Convert byte[] ( array ) to File using Java Example
import java.io.*; 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(); } }