Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java define the size of its primitive types anywhere?

Is there a package that defines the size of Java primitives that I can import in my project? I'm doing some manual bit setting and I keep a byte index. I don't want to do currentByte += 4 when I set an int (magic numbers are frowned upon), I rather do currentByte += <SomePackage>.SIZE_OF_INT

I guess I can define my own, but that's kind of clunky, especially if those are available somewhere.

like image 775
ventsyv Avatar asked Apr 02 '15 15:04

ventsyv


People also ask

What is true about primitive types in Java?

Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.

Why the size of all data types in Java on all platforms are same?

The JVM (Java Virtual Machine) is designed to be platform independent. If data type sizes were different across platforms, then cross-platform consistency is sacrificed. The JVM isolates the program from the underlying OS and platform.

How does Java handle primitive data types?

However, Java provides support for character strings using the String class of Java. lang package. String class has some special support from the Java Programming language, so, technically it is a primitive data type. While using String class, a character string will automatically create a new String Object.

Which statement is true about primitives?

All the primitive types are lowercase, making Option A correct. Unlike object reference variables, primitives cannot reference null. String is not a primitive as evidenced by the uppercase letter in the name and the fact that we can call methods on it. You can create your own classes, but not primitives.


1 Answers

Not a class, but you have Integer.SIZE, and so on for Long and floating point classes too. You also have *.BYTES.

Therefore Integer.SIZE is 32, Integer.BYTES is 4, Double.SIZE is 64 and Double.BYTES is 8, etc etc; all of these are ints in case you were wondering.

NOTE: *.BYTES are only defined since Java 8 (thanks @Slanec for noticing)

(*.SIZE appeared in Java 5 but you do use at least that, right?)

And yes, this is defined by the JDK since the JLS itself defines the size of primitive types; you are therefore guaranteed that you'll have the same values for these constants on whatever Java implementation on whatever platform.

like image 150
fge Avatar answered Sep 28 '22 05:09

fge