What is the size of int in java?
In Java, the size of an int is always 32 bits (4 bytes), regardless of the underlying platform. This is one of Java's "write once, run anywhere" features - the data type sizes are standardized across all implementations.
- Range: -2,147,483,648 to 2,147,483,647 (-2^31 to 2^31-1)
- Size: Exactly 4 bytes (32 bits)
- Default value: 0
This is different from languages like C/C++ where int size can vary by compiler and platform. Java's consistency makes it much easier to write portable code.
Other primitive types in Java:
- byte: 1 byte (-128 to 127)
- short: 2 bytes (-32,768 to 32,767)
- long: 8 bytes (huge range)
- float: 4 bytes
- double: 8 bytes
The Java Language Specification officially defines these sizes if you need authoritative reference.
As a Java developer for over 10 years, I can confirm int is always 4 bytes in Java. Here's why this matters:
Memory considerations:
- Each int variable uses exactly 4 bytes of memory
- In arrays: int[1000] uses about 4,000 bytes + small overhead
- This predictability helps with memory planning
When you might need other sizes:
- Use byte for very small numbers to save memory
- Use long for numbers larger than 2 billion
- Use short for numbers under 32,000 when memory is critical
Common mistake I see: ```java // Don't do this for large numbers: int bigNumber = 3000000000; // This won't compile!
// Do this instead: long bigNumber = 3000000000L; The consistency across Windows, Linux, Mac, and all JVMs is one of Java's best features for cross-platform development.