Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for getting datatype size(sizeof) in Java

Tags:

java

sizeof

I want store a list of doubles and ints to a ByteBuffer, which asks for a size to allocate. I'd like to write something like C's syntax

int size=numDouble*sizeof(double)+numInt*sizeof(int); 

But there is no sizeof in Java. What is the best practice to calculate the size in byte? Should I hardcode it?

like image 701
Wei Shi Avatar asked Jul 20 '11 18:07

Wei Shi


People also ask

How will you find the size of datatype in Java?

The size of a data type is given by (name of datatype). SIZE. The maximum value that it can store is given by (Name of data type). MAX_VALUE.

What determines the size of a data type?

The size or range of the data that can be stored in an integer data type is determined by how many bytes are allocated for storage. Because a bit can hold 2 values, 0 or 1, you can calculate the number of possible values by calculating 2n where n is the number of bits.

What is sizeOf () in Java?

Overview. sizeOf() is a static method of the FileUtils class that is used to get the size of the specified file or directory in bytes. If the file provided is a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively.

Why sizeOf is not in Java?

Similarly, there is is no sizeof() operator in Java. All primitive values have predefined size, e.g., int is 4 bytes, char is 2 byte, short is 2 byte, long and float is 8 byte, and so on.


2 Answers

See @Frank Kusters' answer, below!

(My original answer here was for Java versions < 8.)

like image 177
Ed Staub Avatar answered Sep 18 '22 09:09

Ed Staub


Since Java 8, all wrapper classes of primitive types (except Boolean) have a BYTES field. So in your case:

int size = numDouble * Double.BYTES + numInt * Integer.BYTES; 

Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

like image 20
Frank Kusters Avatar answered Sep 21 '22 09:09

Frank Kusters