Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who decides data types size in Java

Tags:

java

Who decides the size of data types such as int in Java? JVM or OS or Processor?

int size is 4 bytes..Will it be always 4 bytes irrespective of OS or processor?

like image 754
Anand Avatar asked May 26 '12 08:05

Anand


People also ask

Who decides size of data types?

It is strictly, 100%, entirely the compiler that decides the value of sizeof(int). It is not a combination of the system and the compiler. It is just the compiler (and the C/C++ language specifications).

What does the size of data type depend on?

The size of both unsigned and signed long integers depends on the type of compiler that we use. The size is typically about 32-bits or 4 bytes on a 16/ 32-bit compiler. Yet, it varies depending on what compiler we are using.


3 Answers

The Java Language Specification decides them. They're the same size on all VMs, on all OSes, on all processors. If they're not, it's not Java anymore.

like image 69
JB Nizet Avatar answered Oct 07 '22 00:10

JB Nizet


It is the JVM specification that drives JVM implementations to decide the size of data-types. Refer http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.3

like image 39
Ahamed Mustafa M Avatar answered Oct 07 '22 00:10

Ahamed Mustafa M


While the Java spec decides how many bits each type actually uses, the default 32 bit JVM actually pads some types in memory, using 32 bits of space to store values, even ones that don't need that much space. They still all behave (regarding the program), as if they took up their real amount of storage, but the amount of space used is still much larger.

Other JVMs can do this differently, for instance they could store an array of booleans with only one bit per value, rather than 32 bits per value.

So while the size of an int will always appear to be 32 bits, because it will always wrap around at 32 bits and can only hold 32 bit values, the JVM does have the option of internally storing it using 64 bits of space, or some other number depending on the hardware and implementation.

Also, floating point values are actually much less restricted in this regard - while the spec for float and double does indeed require they use a particular format, the presence of the two different libraries java.lang.Math and java.lang.StrictMath (see What's the difference between java.lang.Math and java.lang.StrictMath? for an explanation) is a clear example. Using java.lang.Math does not require that the intermediate calculations for those functions be stored in any particular way, or that it use a particular number of bits to compute everything.

like image 43
AJMansfield Avatar answered Oct 07 '22 00:10

AJMansfield