'How does a byte[] in java actually store data

If I have the following:

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

I know that the size of each element would be one byte. But what I don't seem to understand is how would the integer 87 be stored in one byte? Or, how does the byte[] store data?

EDIT: I see that you can store -128 to 127 in a byte here in java. So, does that mean there is no way to store anything greater than or lesser than those numbers in a byte[]? If so, doesn't that limit the use of this? Or am not understanding the exact places to use a byte[].



Solution 1:[1]

A byte is 8 bits. 2^8 is 256, meaning that 8 bits can store 256 distinct values. In Java, those values are the numbers in the range -128 to 127, so 87 is a valid byte, as it is in that range.

Similarly, try doing something like byte x = 200, and you will see that you get an error, as 200 is not a valid byte.

Solution 2:[2]

A byte is just an 8-bit integer value. Which means it can hold any value from -2^7 to 2^7-1, which includes all of the number in {87, 79, 87, 46, 46, 46}.

An integer in java, is just a 4-byte integer, allowing it to hold -2^31 to 2^31 - 1

Solution 3:[3]

A Java byte is a primitive with a minimum value of -128 and a maximum value of 127 (inclusive). 87 is within the allowed range. The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters.

A byte[] is an Object which stores a number of these primitives.

Solution 4:[4]

I think the short answer is that byte[] stores bytes. The number 87 in your array above it a byte, not an int. If you were to change it to 700 (or anything higher than 127) you'd get a compile error. Try it.

Solution 5:[5]

You can use byte to store values of 8 bit in it which have a (signed) range from from -128 to 127.

With byte[] you can do some special operations like building Strings from a given bytestream and decode them with a desired Charset, and some functions will give you byte[] as their return value.

I don't know enough about the internals of the JVM but it might save memory though.

Solution 6:[6]

this is because, the computer stores values in a circular progression. not a linear progression like we learn in mathematics. it is because the memory is not infinite. it is finite. so every data type is storing values as a circular progression. to learn more go to this link and read the article.

https://medium.com/@hmsathyajith/numbering-system-edge-cases-of-java-237377553444

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Newmuis
Solution 2 Rob Wagner
Solution 3 Reimeus
Solution 4 Mason Bryant
Solution 5 nkr
Solution 6 Sathyajith Saliya