Java Data Types
Java Data Types and memory mapping details
Java Data Types are divided broadly into three categories.
- Primitive Data Type
- Derived Data Type
- User Defined Data Types
Primitive Data Types
- byte
- short
- int
- long
- float
- double
- char
- boolean
[addToAppearHere]
Data Type | Size | Range | Default Value(when present as instance or static field ) |
boolean | 1 bit | true/ false | false |
char | 2 byte | 232767 to -32768 | ‘\u0000’ |
byte | 1 byte | + 127 to -128 | 0 |
short | 2 byte | + 32767 to -32768 | 0 |
int | 4 byte | −2,147,483,648 to 2,147,483,647 | 0 |
long | 8 byte | 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807 |
0L |
float | 4 byte | 3.4e−038 to 3.4e+038 | 0.0f |
double | 8 byte | 1.7e−308 to 1.7e+038 | 0.0d |
char is of 2 byte in Java, but depending on the encoding set on the Platform it can assume 1 byte (ISO-8859-1 or UTF-8 encoding) or 2 bytes(UTF-16 encoding). Hence one should explicitly mention the encoding while converting from byte[] to char[].
Derived Data types
primitive data Type arrays ( int[] a )
User Defined Data Types
- Classes
- Enum
- Interfaces
Size of a class : size of a class is sum total of the size of all the instance member + some(extra bytes for padding + virtual pointers).
[addToAppearHere]
There are many perspective to look at what data Type exactly means. The two most important perspective are
- memory footprint of the data Type.
- How to interpret the raw bytes to the values we see in the language.
- operations which can be performed on the data type.
Lets take example of char(1 byte) and short both consume only 1 byte in memory yet how we interpret the byte is different.We apply operations like addition subtraction on short and not on char.
Memory Mapping of primitive, Derived and User Defined Data Types.
intVar allocated 4 bytes and stores 1 in it.
int intVar = 1;
intArrayVar allocates 4 Bytes * 3 = 12 bytes and stores 1,2,3 contiguously.
int[] intArrayVar = {1,2,3};
reference allocates 4 bytes and stores the address of ParentClass object. ParentClass object is stored in a different location in heap.
ParentClass reference = new ParentClass();
class ParentClass {
protected int parentState = 10;
public String getState(){
return "parentState value is " + parentState;
}
}