5

Hi I am learning Java basics. I need to check the size of primitive data types like using sizeof(); in c language.

Example code:

int i;
System.out.print(sizeof(i));
4
  • 2
    possible duplicate of In Java, what is the best way to determine the size of an object? Commented Aug 19, 2015 at 11:55
  • 3
    If you type the title of your question into Google the first result gives you the answer Commented Aug 19, 2015 at 11:57
  • For which purpose you need this? Commented Aug 19, 2015 at 12:04
  • Not for any specific purpose! Just need to know if any possibilities. Commented Aug 19, 2015 at 12:06

2 Answers 2

10

Use the BYTES constants (since Java 8) in the corresponding boxed classes:

sizeof(int) -> Integer.BYTES
sizeof(long) -> Long.BYTES
sizeof(char) -> Character.BYTES
sizeof(short) -> Short.BYTES
sizeof(float) -> Float.BYTES
sizeof(double) -> Double.BYTES
sizeof(byte) -> Byte.BYTES

Note that reference and boolean sizes are not defined, it's implementation-specific. In general you rarely should care about their size.

Sign up to request clarification or add additional context in comments.

1 Comment

Pre java-8 you could use the SIZE constant, just need to know that they give the representation in bits instead of bytes.
9

There's no need for such a thing in Java since the sizes of the primitives are set for all JVMs (unlike C where they can vary).

char is 16 bit (actually an unsigned quantity), int is 32 bit, long is 64 bit.

boolean is the ugly sister in all this. Internally it is manipulated as a 32 bit int, but arrays of booleans use 1 byte per element.

3 Comments

I see no reason to call boolean the ugly sister. Internally bytes, shorts and chars are also often manipulated as 32-bit integers. User just should not care about these internals.
@TagirValeev The fact is that there is no language definition for the size of boolean. All the rest of the types have that size defined in their wrapper classes (SIZE constant representing number of bits). You can write all types into a ByteBuffer - except boolean, etc.
@RealSkeptic, your comment sounds reasonable, but the "Internally it is manipulated as a 32 bit int" statement in the answer is not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.