Why does ByteArrayOutputStream use int?

Maybe someone can help me understand, because I feel that I am missing something that is likely to affect my program.

I am using ByteArrayOutputStream. If I have not missed something huge, then this class should create a byte [] array for other uses.

However, the "simple" write function in BAOS accepts int not bytes ( ByteArrayOutputStream.write ).

According to this ( Primitive Data Types ), in Java, int is a 32-bit data type, and a byte is an 8-bit data type.

If I write this code ...

int i = 32;
byte b = i;

I get a warning about possible lossy transformations requiring a change to this ...

int i = 32;
byte b = (byte)i;

I am really confused about the entry (int) ...

+4
3

ByteArrayOutputStream , OutputStream. , OutputStream.write(int) , , . .

- , -, . , , :

, , - b. 24 b .

( ), write(byte). , :

// Write a single byte 0. Works with current code, wouldn't work if the parameter
// were byte.
stream.write(0);

, , 0 int, byte. :

// Ugly, but would have been okay with write(byte).
stream.write((byte) 0);

API , , , - Java 1.0. , , , , .

+4

0x7F, . Int , . , (byte).

Ingo:

, , int [, ] . , , .

+5

, Java Virtual Machine byte, int. 32- , int.

, java * does * byte[] . , ( ). , byte ( bipush sipush), .

Java 257 (!). InputStream#read() 256 , , -1. EOFException ( ), java .

-1 OutputStream#write , . , .

0
source

Source: https://habr.com/ru/post/1524348/


All Articles