Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

Why is there no sizeof in Java?

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?

Upvotes: 13

Views: 2517

Answers (7)

Hanu
Hanu

Reputation: 57

To enhance the security of Java application, one way is not to allow the programmer to fiddle with memory. So not providing sizes of primitives is one such decision. Similarly, memory management is also not done by programmer but by JVM.

Upvotes: 0

Ysp
Ysp

Reputation: 312

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.

Upvotes: 1

user949300
user949300

Reputation: 15729

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.

Upvotes: 0

Samizdis
Samizdis

Reputation: 1671

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

Upvotes: 0

MByD
MByD

Reputation: 137392

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.

Upvotes: 1

maerics
maerics

Reputation: 156592

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.

Upvotes: 22

rabusmar
rabusmar

Reputation: 4143

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.

Upvotes: 7

Related Questions