How to initialize a byte array in Java
Codemia Knowledge Hub ·
Use new byte[size] for a zero-filled array, or an array literal such as {10, 20, 30} when you know the values up front. To set values afterwards, use a for loop or Arrays.fill(). Java's byte is an 8-bit signed integer ranging from -128 to 127, and byte arrays are the usual container for binary data from files, images and streams.
new byte[n]: default zero values
All 10 elements start at zero.
Array literal
Filling with a for loop
For a pattern or computed values:
Each element becomes its index multiplied by 10.
Arrays.fill() for a single value
Every element is set to 1.
Streams (boxed Byte[] only)
There is no primitive ByteStream, so toArray(Byte[]::new) produces a boxed Byte[], not a byte[], so the variable is declared as Byte[]. Assigning the result to byte[] does not compile; use a for loop when you need a primitive byte[].
Comparing the methods
| Method | Example | Description |
| Default | new byte[10] | All elements initialized to zero. |
| Literal | {10, 20, 30} | Directly initializes with specified values. |
| For Loop | for (int i = 0; ...) { byteArray[i] = ... } | Allows custom patterns or manipulations. |
| Arrays.fill | Arrays.fill(byteArray, (byte) 1); | Sets all elements to a specified default value. |
| Streams | IntStream.range(0, n)...toArray() | Functional style; yields a boxed Byte[]. |
Multi-dimensional byte arrays
A two-dimensional byte array suits grid-like data such as images.
Size, memory and bounds
- Fixed length: an array's length is fixed once it is created.
- Memory: byte arrays are more memory-efficient than character arrays for non-text binary data.
- Bounds: accessing an index outside the array throws
ArrayIndexOutOfBoundsException. Check indexes before use.
Byte arrays are common with FileInputStream and FileOutputStream for binary file I/O, and with socket streams in network code.
Related reading
- How do I instantiate a Queue object in java?
- How do I iterate over Binary Tree?
- How do I iterate through two lists in parallel?
- How do I join two lists in Java?
- How do I install Java on Mac OSX allowing version switching?
- How do I invoke a Java method when given the method name as a string?
- How do I list all files of a directory?
- How do I list all the columns in a table?
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.