8

I am wondering if long is 64 bits in both x86 and x64?

Kai
  • 38,985
  • 14
  • 88
  • 103
user705414
  • 20,472
  • 39
  • 112
  • 155

5 Answers5

34

Yes. A Java long is 64 bits on any JVM, without exception. All the Java primitive types are completely portable and have fixed sizes across all implementations.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 5
    JLS reference: http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3 – Mat Jan 06 '12 at 15:08
5

The primitive types are always the same size. Only references can change in size, but you generally don't need to know this.

You can get the size of a reference with

int addressSize = Unsafe.addressSize();

Note: Even in a 64-bit JVM (on the latest Java 6+ JVMs), references are 32-bit but unless you use a 32 GB heap or larger. This is the default on the OpenJDK/Sun/Oracle JDK, however as @user988052 notes, the IBM JVM needs the appropriate flag to be set on the command line. Other JVMs might not support this option at all.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • *Even in a 64-bit JVM (on the lateset Java 6+ JVMs), references are 32-bit unless you use a 32 GB heap or larger*... Isn't that JVM dependent? *-XX:+UseCompressedOOps* on Oracle/Sun JVMs is now indeed the default as far as I know but apparently the IBM JVM, for example, specifies that if you do *not* use their *Xcompressedrefs* VM parameter, then the references are stored on 64-bits by default... – TacticalCoder Jan 06 '12 at 16:12
4

Yes. A long is known as a 64-bit Integer.

0

Yes by definition, but beware declarations of longs using literals:

final long num = 1000 * 1000 * 1000 * 3; // Looks fine, right ?
System.out.println("num=" + num);
Prints: num=-1294967296

So the num is negative... due to an overflow !!!

Also see this post (C# but similar): 1000000000 * 3 = -1294967296?

Solution: you must specify it is a long using L somewhere:

final long num = 1000 * 1000 * 1000 * 3L;
System.out.println("num=" + num);
Prints: num=3000000000

The bad thing is that this will not cause issues as long as the number is small enough, the compiler will not complain ... so this causes issues at runtime, depending on your code you may not even notice the issues.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
0

Yes long is alwyas a 64 bit in Java because it is platform independent but in C++ if the machine is of 32 bits or of 64 bits then it's size may vary. For eg: int is of size 32 bits in C++ in 64 bit machine but in 32 bit machine the size is 16 bits only.

Vishal Senjaliya
  • 454
  • 6
  • 21
N.Neupane
  • 281
  • 1
  • 4
  • 17