简体   繁体   中英

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[] .

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.

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

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.

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.

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 String s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM