Ankit Sachan Ankit Sachan - 3 months ago 9
Java Question

Is there any sizeof-like method in Java?

Is there any built-in method in Java to find the size of any datatype?
Is there any way to find size?

Answer

No. There is no such method. It is not needed in Java, since the language removes the need for an application to know about how much space needs to be reserved for a primitive value, an object or an array with a given number of elements.

You might think that a sizeof operator would be useful for people that need to know how much space their data structures take. However you can also get this information and more, simply and reliably using a Java memory profiler, so there is no need for a sizeof method.


@Davor makes the point that sizeof(someInt) would be more readable than 4. I'm not sure that I agree ... because I think that every Java programmer ought to know that an int is always 32 bits (4 bytes). (And besides, it is rarely necessary to use the size of a type in Java code ...)

However if you accept that readability argument, then the remedy is in your hands. Simply define a class like this ...

public class PrimitiveSizes {
    public static int sizeof(byte b) { return 1; } 
    public static int sizeof(short s) { return 2; }
    // etcetera
}

... and statically import it ...

import static PrimitiveSizes.*;

Why haven't the Java designers implemented this in standard libraries? My guess is that:

  • they don't think there is the demand, and / or
  • they don't think it is worth the effort.

The key word in the above is they. (It does not matter what you or I think about it ... unless you have some influence in the decision making process.)

There is also the issue that the next demand would be for a sizeof(Object o) method, which is fraught with technical difficulties.