In Java, data types specify the size and type of values that can be stored in a variable.
Java is a statically-typed programming language means that all variables must be declared before they are used.
In Java, data types are of 2 types:
- Primitive data types: 1.It includes boolean, char, byte, short, int, long, float and double. It is also known as intrinsic data type.
- Non-Primitive data types: It includes Classes, Interfaces, and Arrays. It is also known as object/reference data type.
Primitive Data Types
Primitive data types in java are predefined by the language and named by a keyword.
Java supports 8 Primitive data types:
1. Boolean Data Type
Java boolean data type can store only 2 possible values i.e. true and false.
We mainly uses this data type for simple flags that track true/false conditions.
Boolean flag = false;
2. Char Data Type
Java char data type is a single 16-bit unicode character. Its value lies between '0’ to ‘65,535’ (inclusive).
It is used to store character which represents character sets like numbers and letters.
char ch = 'T';
3. Byte Data Type
Java byte data type is a 8-bit signed 2's complement integer. Its value lies between -128 to 127 (inclusive).
It is used to save memory in large arrays because byte data type is 4 times smaller than an integer.
byte a = 17, b = -69;
4. Short Data Type
Java short data type is a 16-bit signed 2's complement integer. Its value lies between -32,768 to 32,767 (inclusive).
It is used to save memory in large arrays because short data type is 2 times smaller than an integer.
short x = 136, y = -754;
5. Int Data Type
Java int data type is a 32-bit signed 2's complement integer. Its value lies between -2,147,483,648 (-231) to 2,147,483,647 (231 -1) (inclusive).
It is used as a default data type for integral values.
int a = 17, b = -23;
6. Long Data Type
Java long data type is a 64-bit 2's complement integer. Its value lies between -9,223,372,036,854,775,808 (-2^63) to 9,223,372,036,854,775,807 (2^63 -1) (inclusive).
It is used when we need a range of values wider than those provided by integers.
long a = 38L, b = -86L
7. Float Data Type
Java float data type is a single precision 32-bit IEEE 754 floating point. Its value is unlimited.
We should never use this data type for precise values such as currency.
float flt1 = 11.3f
8. Double Data Type
Java double data type is a double precision 64-bit IEEE 754 floating point. Its value is also unlimited.
It is used as the default data type for decimal values.
double d1 = 73.2
Non-Primitive Data Types
Non-primitive variables are created using defined constructors of the classes.
These variables are declared to be of a specific type that cannot be changed in our program.
Null is the default value of any reference variable.
There are 3 types of non-primitive data types: