Is there any built-in method in Java to find the size of any datatype?
Is there any way to find size?
Is there any built-in method in Java to find the size of any datatype?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No. There is no such method in the standard Java SE class library.
The designers’ view is that it is not needed in Java, since the language removes the need for an application1 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.
Previous commenters made the point that
sizeof(someType)would be more readable than4. If you accept that readability argument, then the remedy is in your hands. Simply define a class like this …… and statically import it …
Or define some named constants; e.g.
Or (Java 8 and later) use the
Integer.BYTESconstant, and so on.Why haven’t the Java designers implemented this in standard libraries? My guess is that:
There is also the issue that the next demand would be for a
sizeof(Object o)method, which is fraught with technical difficulties.The key word in the above is "they"!
1 – A programmer may need to know in order to design space efficient data structures. However, I can’t imagine why that information would be needed in application code at runtime via a method call.