tags:

views:

233

answers:

5

Given Java's "write once, run anywhere" paradigm and the fact that the Java tutorials give explicit bit sizes for all the primitive data types without the slightest hint that this is dependent on anything, I would say that, yes, an int is always 32 bit.

But are there any caveats? The language spec defines the value range, but says nothing about the internal representation, and I guess that it probably shouldn't. However, I have some code which does bitwise operations on int variables that assume 32 bit width, and I was wondering whether that code is safe on all architectures.

Are there good in-depth resources for this type of question?

+11  A: 

Java code always works as though ints are 32-bit, regardless of the native architecture.

In the specification, there's also a part that is definitive about representation:

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units

Adam Crume
I found the quote later after some more digging around in the spec and added it.
Hanno Fietz
+1  A: 

Yes, there is no sizeof operator in Java.

According to Bruce Eckel's Thinking in Java:

  • short: 16 bits
  • int: 32 bits
  • long : 64 bits

These values don't vary between architectures.

Tom
+1  A: 

you may be check also the JVM specs: each bitwise operation gets it's opcode (ISHL, IOR, IAND, etc)

dfa
+4  A: 

While the behaviour of Java's primitives is specified completely and exactly in the language spec, there is one caveat: on a 64bit architetcture, it's possible that ints will be word-aligned, which means that an array of ints (or any non-64bit primitive type) could take twice as much memory as on a 32bit achitecture.

Michael Borgwardt
A: 

This isn't an answer because there is already a good answer but I thought I'd point out that the reason this is so for Java but it wasn't for C or C++ is that Java compiles to a virtual machine (the Java VM or JVM). Because the JVM runs the same bytecode and has the same internal structure no matter which machine it is on, it seems to have the same size for primitive types on every machine. C and C++ did not try to emulate any particular behaviors and were subject to the whims of processor implementations on a variety of machines.

John Munsch
Whether a language is compiled to bytecode and whether it has cross platform primitive sizes are independent.
Tom Hawtin - tackline