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:
public static void main(String[] args)< // Declaration of byte array byte[] myfirstarray = new byte[10]; >
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>
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
What is Java Byte Array and How should it be used?
@SpencerStewart Well, this is a very basic topic, should be mentioned in any decent tutorial, even 4 years ago, when the question was asked. But I guess that now, due to the high popularity of this site you found this (bad) question.
@TDG There are many questions on this site that are basic programming 101 type questions. The question itself wasn’t bad, it definitely could have been worded better and needs some punctuation and grammar corrections. I may be wrong but the question fits in fine with this site. We’re striving to be a definitive wiki-like resource for programming questions. I googled for byte array because I wasn’t sure if there was anything special about it other than being a literal array with byte values inside of it. Evan Williams’ answer was perfect and what I was hoping for.
1 Answer 1
By byte array, it literally means an array where each item is of the byte primitive data type. If you do not know the difference between a byte and a common int (Integer), the main difference is the bit width: bytes are 8-bit and integers are 32-bit. You can read up on that here.
If you do not know what an array is, an array is basically a sequence of items (in your case a sequence of bytes, declared as byte[] ).
The function a.getBytes() takes a , which is a String, and returns an array of bytes. This can be done because the human-readable characters in a String can be represented as 8-bit numbers, where the mapping between number and character is determined by the CharSet. Examples of two common CharSets are ASCII and UTF-8. Now, arr is an array of bytes, where each byte in the array represents each character in the original string a . In both ASCII and UTF-8, the String «32» is represented by the bytes 51 and 50 in decimal, and 0x33 and 0x32 in hexadecimal.
Byte arrays are commonly used in applications that read and write data byte-wise, such as socket connections that send data in byte streams through TCP or UDP protocols.
Purpose of byte type in Java
byte: The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable’s range is limited can serve as a form of documentation.
I’ve gave an answer, but whoever wrote this tutorial, in my opinion it’s just BS. Nobody should fool themselves by thinking it’s a proper form of documentation.
I don’t think they mean it as a replacement for actual documentation. They’re probably saying that by reading byte, you automatically think of the scope of the values, unlike int where the range is so big you just think number.
7 Answers 7
Byte has a (signed) range from -128 to 127, where as int has a (also signed) range of −2,147,483,648 to 2,147,483,647.
What it means is that since the values you’re going to use will always be between that range, by using the byte type you’re telling anyone reading your code this value will be at most between -128 to 127 always without having to document about it.
Still, proper documentation is always key and you should only use it in the case specified for readability purposes, not as a replacement for documentation.
If you’re using a variable which maximum value is 127 you can use byte instead of int so others know without reading any if conditions after, which may check the boundaries, that this variable can only have a value between -128 and 127.
So it’s kind of self-documenting code — as mentioned in the text you’re citing.
Personally, I do not recommend this kind of «documentation» — only because a variable can only hold a maximum value of 127 doesn’t reveal it’s really purpose.
Integers in Java are stored in 32 bits; bytes are stored in 8 bits.
Let’s say you have an array with one million entries. Yikes! That’s huge!
Now, for each of these integers in foo , you use 32 bits or 4 bytes of memory. In total, that’s 4 million bytes, or 4MB.
Remember that an integer in Java is a whole number between -2,147,483,648 and 2,147,483,647 inclusively. What if your array foo only needs to contain whole numbers between, say, 1 and 100? That’s a whole lot of numbers you aren’t using, by declaring foo as an int array.
This is when byte becomes helpful. Bytes store whole numbers between -128 and 127 inclusively, which is perfect for what you need! But why choose bytes ? Because they use one-fourth of the space of integers. Now your array is wasting less memory:
byte[] foo = new byte[1000000];
Now each entry in foo takes up 8 bits or 1 byte of memory, so in total, foo takes up only 1 million bytes or 1MB of memory.
That’s a huge improvement over using int[] — you just saved 3MB of memory.
Clearly, you wouldn’t want to use this for arrays that hold numbers that would exceed 127, so another way of reading the bold line you mentioned is, Since bytes are limited in range, this lets developers know that the variable is strictly limited to these bounds. There is no reason for a developer to assume that a number stored as a byte would ever exceed 127 or be less than -128. Using appropriate data types saves space and informs other developers of the limitations imposed on the variable.
I imagine one can use byte for anything dealing with actual bytes.
Also, the parts (red, green and blue) of colors commonly have a range of 0-255 (although byte is technically -128 to 127, but that’s the same amount of numbers).
There may also be other uses.
The general opposition I have to using byte (and probably why it isn’t seen as often as it can be) is that there’s lots of casting needed. For example, whenever you do arithmetic operations on a byte (except X= ), it is automatically promoted to int (even byte+byte ), so you have to cast it if you want to put it back into a byte .
A very elementary example:
FileInputStream::read returns a byte wrapped in an int (or -1). This can be cast to an byte to make it clearer. I’m not supporting this example as such (because I don’t really (at this moment) see the point of doing the below), just saying something similar may make sense.
It could also have returned a byte in the first place (and possibly thrown an exception if end-of-file). This may have been even clearer, but the way it was done does make sense.
FileInputStream file = new FileInputStream("Somefile.txt"); int val; while ((val = file.read()) != -1) < byte b = (byte)val; // . >
If you don’t know much about FileInputStream , you may not know what read returns, so you see an int and you may assume the valid range is the entire range of int (-2^31 to 2^31-1), or possibly the range of a char (0-65535) (not a bad assumption for file operations), but then you see the cast to byte and you give that a second thought.
If the return type were to have been byte , you would know the valid range from the start.
Another example:
One of Color’s constructors could have been changed from 3 int ‘s to 3 byte ‘s instead, since their range is limited to 0-255.