0

I am learning about Java and I have the code as below:

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        try (DataOutputStream testFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("test_file.txt")))) {
            testFile.writeInt(4);
        }
    }
}

The code above would write the number 4 as binary into the byte stream then appending it to the text_file.txt but when I checked the writeInt() method of the DataOutputStream class, it is shown as:

public final void writeInt(int v) throws IOException {
    out.write((v >>> 24) & 0xFF);
    out.write((v >>> 16) & 0xFF);
    out.write((v >>>  8) & 0xFF);
    out.write((v >>>  0) & 0xFF);
    incCount(4);
}

I did some research about >>> and & from here and here but still I can not figure out what the code above really doing under the hood

Can someone elaborate more for me on this ?

Kind regards,

Ken

Ken Masters
  • 239
  • 2
  • 17
  • 1
    What don't you understand about the two linked posts? Are you aware that an `int` has 4 bytes? – Sweeper Feb 03 '23 at 04:12
  • @Sweeper, why does the out.write() call 4 times with different parameters ? What does the parameters themselves mean for the out.write() ? – Ken Masters Feb 03 '23 at 04:17
  • 2
    Well, an `int` has 4 bytes in it, and all 4 of them needs to be written. Each `write` call writes one of the bytes in the `int`. That's why I asked you, "are you aware that an int has 4 bytes?" – Sweeper Feb 03 '23 at 04:25
  • ohhh, it means that the v >>> 24 shifts the first 8 bits to the right most part and the (v >>> 24) & 0xFF makes the leading 24 bits to 0 - then the resultant bits is written into the file. Each of the next out.write() method, it writes the next 8 bits into the byte stream. Hope that my understanding correctly :) – Ken Masters Feb 03 '23 at 04:40

0 Answers0