13

For what design reason there is no sizeof operator in java? knowing that it is very useful in c++ and c# and how you can get the size of a certain type if needed?

Sleiman Jneidi
  • 22,151
  • 12
  • 53
  • 74

5 Answers5

22

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.

maerics
  • 143,080
  • 41
  • 260
  • 285
7

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.

rabusmar
  • 3,974
  • 1
  • 24
  • 28
  • I know sometimes it might be of use, but, as @maerics pointed out, probably the designers didn't think it was necessary to add it to the language specification. There are still ways to know an object's size tho, check one of the question comments for that. – rabusmar Dec 01 '11 at 18:33
1

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.

Community
  • 1
  • 1
MByD
  • 133,244
  • 25
  • 260
  • 270
0

Memory management is done by the VM in Java, perhaps this might help you: http://www.javamex.com/java_equivalents/memory_management.shtml

Samizdis
  • 1,481
  • 1
  • 17
  • 32
0

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.

user949300
  • 15,154
  • 6
  • 33
  • 65