Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

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

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.

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.

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

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.

c language has its own advantage of varying the data type size. that time main memory is not too much...every programmer has to write code that is space optimized.

nowadays space is no more a issue...a portable program is much more preferable.

that why to make java portable java do not support varying size datatypes

because java is platform independent language. that's why in java size of data type is fixed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top