views:

380

answers:

6

In C as we know the size of data types (ex. int) can vary depending on compiler / hardware.

But why the size of data types is constant in java language? why don't we have the flexibility for different data type size in java depending on compiler?

+12  A: 

If data type size varies on different platforms you lose portability.

Buhb
+1  A: 

The flexibility of C for this has some advantages (reduced memory/storage consumption if you use 32 instead of 64 bits), but these advantages tend to become less relevant as the hardware improves (this was designed in the 70s).

This flexibility however comes with severe interoperability and long-term vision problems (Y 2038 bugs).

In contrast, a Java object has anyway some storage overhead, so saving 4 bytes on each Date object would be quite pointless and only troublesome.

Zorglub
+2  A: 

Because that's Java. See the Java language specification.

michael.kebe
+13  A: 

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. This can make life difficult for performing system-specific work, but the benefits are that you can write-once, run-anywhere (this is largely true, with some unfortunate issues. Write-once, test-everywhere is a much more practical approach).

Brian Agnew
+3  A: 

To get a really comprehensive answer to this, you'd need to do a great deal of historical reading from the early days of Java. Certainly, the designers could have included a more complicated primitive type system. However, when Java burst onto the broad stage, it was aimed at applets. Code to run in a browser, organizing complex UI, didn't (and doesn't) need to know whether it is running on the infamous MNS-49 (7 7-bit chars per word), or the Honeywell 68000 (4 9-bit chars per word), or a boring modern processor. It's much more important than anyone can code bit arithmetic on an int and know what's going to happen after 32 shifts.

bmargulies
Actually java started out as the Oak project, which was aimed at embedded devices. Then when the web exploded they realized it would work really well for applets, too.
Chad Okere
edited accordingly.
bmargulies
+1  A: 

The idea of java was "Write once, Run anywhere" without recompiling. That means every VM has the same data size. Of course, on 64 bit machines, it uses 64 bit references, but you don't have access to those so it doesn't matter.

It works pretty well, but one thing I do wish is that wish we could get 64 bit array indexes. This didn't really matter back in the day, but for large memory mapped files it's a huge pain. You have to break them up into 2gb chunks.

Chad Okere
Do you really need that? *oh*Is there a bug on this in the SUn bug parade?
Thorbjørn Ravn Andersen