Search code examples
javabytearrayinputstream

ByteArrayInputStream does not copy the byte array?


The Documentation on ByteArrayInputStream says :

java.io.ByteArrayInputStream.ByteArrayInputStream(byte[] buf) Creates a ByteArrayInputStream so that it uses buf as its buffer array. The buffer array is not copied. The initial value of pos is 0 and the initial value of count is the length of buf. Parameters: buf the input buffer.

When I run the below code ,

        byte[] b = new byte[10];
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    String someText = "Java byte arrayinput stream test - this string will be used.";
    b = someText.getBytes();

    int c =0;
    while( ( c = bais.read()) != -1 ){
        System.out.print((char)c);
    }

the output I get is based on the 10 byte blank array, not the string used to test. This indicates that the constructor of ByteArrayInputStream must be copying the byte array rather than storing a reference to the passed byte array.This contradicts the documentation. Can anyone clarify my understanding , if the byte array is copied or not ?( and if it is not copied , then why the output does not reflect the state of byte array b ?


Solution

  • You misunderstand how Java variables work.

    This statement creates a new byte[] and assigns it to the variable b:

    byte[] b = new byte[10];
    

    This statement creates another new byte[], and also assigns it to the variable b, replacing the former contents of that variable:

    b = someText.getBytes();
    

    You pass the original value stored in b to the ByteArrayInputStream constructor. Internally, the stream has its own variable, which is assigned a value by the constructor. Afterwards, you change the program's variable, but doing so does not change the stream's variable.