Prev Next
Java is a strongly typed language. Hence every element to be declared, must strictly define its type.
Example:
1 2 |
int x =10; char c; |
Here, x is a variable of the type ‘int’ which is initialized by a value of 10 and c is a variable of type ‘char’.
There are two kinds of data type in Java. They are,
- Primitive data type
- Reference type
1. Primitive Data Type:
- Java defines 8 primitive data types – byte, short, int, long, float, double, char, Boolean.
- The primitive types byte, short, int, long – represents signed integer values.
byte:
- Description: Smallest integer type. Useful to work with raw binary data. E.g data from a network or file.
- Size (in Byte): 1
- Range: -128 to 127
Example:
1 |
byte b=5; |
short:
- Description: 16 bit signed integer type. Least used.
- Size (in Byte): 2
- Range: -32,768 to 32,767
- Example: short num=5;
int:
- Description: Signed 32 bit type. Commonly used in expressions which requires a larger range; also to control loops, index arrays.
- Size (in Byte): 4
- Range: -2,147,483,648 to 2,147,483,647
Example:
1 |
int i=567; |
long:
- Description: Signed 64 bit type and used when ‘int’ is not enough to hold the value.
- Size (in Byte): 8
- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Example:
1 |
long num=2233720368; |
float:
- Description: Real numbers. Decimal with a single precision.
- Size (in Byte): 4
- Range: 1.4e–045 to 3.4e+038
Example:
1 |
float temp=52.5; |
double:
- Description: Decimal with double precision. Math functions like sin(), cos() and sqrt() return double values.
- Size (in Byte): 8
- Range: 4.9e–324 to 1.8e+308
Example:
1 |
double sal= 0.50; |
char:
- Description: Data type to store characters. Unicode values are used to store characters.
- Size (in Byte): 2
- Range: 0 to 65,536
Example:
1 |
char ch = ‘d’; |
boolean:
- Description: Data type to store logical value i.e. true or false. This type is returned by all relational operators and required by conditional expressions like ‘if’ and ‘for’.
- Stores either “true” or “false”
Example:
1 |
boolean flag=true; |
2. Reference Type:
- A reference type is a data type that refers to an object in memory. They can be instantiated.
- Reference type does not store the actual value, but stores the address. References are of type class, interface and array.
Example:
1 2 |
String st = new String(); // st is a reference variable of reference type 'String' Bird b1; |