For what design reason is there no sizeof
operator in Java? Knowing that it is very useful in C++ and C#, how can you get the size of a certain type if needed?
Because the size of primitive types is explicitly mandated by the Java language. There is no variance between JVM implementations.
Moreover, since allocation is done by the new
operator depending on its argument there is no need to specify the amount of memory needed.
It would sure be convenient sometimes to know how much memory an object will take so you could estimate things like max heap size requirements but I suppose the Java Language/Platform designers did not think it was a critical aspect.
In c is useful only because you have to manually allocate and free memory. However, since in java there is automatic garbage collection, this is not necessary.
In java, you don't work directly with memory, so sizeof
is usually not needed, if you still want to determine the size of an object, check out this question.
Memory management is done by the VM in Java, perhaps this might help you: http://www.javamex.com/java_equivalents/memory_management.shtml
C needed sizeof because the size of ints and longs varied depending on the OS and compiler. Or at least it used to. :-) In Java all sizes, bit configurations (e.g. IEEE 754) are better defined.
EDIT - I see that @Maerics provided a link to the Java specs in his answer.
Size of operator present in c/c++ and c/c++ is machine dependent langauge so different data types might have different size on different machine so programmes need to know how big those data types while performing operation that are sensitive to size. Eg:one machine might have 32 bit integer while another machine might have 16 bit integer.
But Java is machine independent langauge and all the data types are the same size on all machine so no need to find size of data types it is pre defined in Java.
© 2022 - 2024 — McMap. All rights reserved.
size()
is sufficient for a givenStructure
. Even object wrapper classes for primitive types (Integer, Byte, etc.) provideSIZE
constant. – Floating