Java is a strongly typed language, that is, when you declare a variable, you need to specify what type of variable it is. Primitive data types are the fundamental data types provided by Java.
Primarily there are 4 categories of primitive types provided by Java. Those are integers, floating point, character and boolean.
Integer type primitives:
Type | Size | Min Value | Max Value |
---|---|---|---|
byte | 8 bit | -128 | 127 |
short | 16 bit | -32768 | 32767 |
int | 32 bit | -2147483648 | 2147483647 |
long | 64 bit | -9223372036854775808 | 9223372036854775807 |
An integer literal value by default is of type int
. A long
type literal needs to end with ‘L’.
byte v1 = 127;
short v2 = 32767;
int v3 = 2147483647;
long v4 = 9223372036854775807L;
Floating type primitives
Type | Size |
---|---|
float | 32 bit |
double | 64 bit |
Floating point type variables can store values that contain fractional portion. By default Java consider a floating point value as double
. If you want the value to be stored in float
type variable, that value needs to end with ‘f’.
float var1 = 25.5f;
double var2 = 25.5;
Character type primitives
Type | Size | Min Value | Max Value |
---|---|---|---|
char | 16 bit | 0 | 65536 |
To store a single character, we can use char
type. Java supports Unicode to represent a character, that means, it can represent any character found worldwide.
Character type literals are placed within single quotes.
char c1 = 'A';
You can also store a Unicode character as follow:
char c2 = '\u20B9'; // Indian rupee Unicode representation
You can also store a integer to represent a character as follows:
char c3 = 8377; // Indian rupee numerical representation
Boolean type primitive
Type | Size | Supported Values |
---|---|---|
boolean | 1 bit | true / false |
When you want to store the result of a condition, we use boolean
type. Its values are true
and false
.
boolean b1 = true;
boolean b2 = false;
boolean b3 = 5 > 2; // since, 5 is greater than 2, b3 will be true