In Java, data types specify the type of data that a variable can hold.
Each data type has specific characteristics and ranges of values it can represent and it is crucial for efficient memory usage and ensuring proper handling of data in Java programs.
Java supports two categories of data types:
Primitive Data Types
Reference Data Types
Here's an example of data types in Java:
Primitive data types represent basic data values and are predefined by the Java language. They are not objects and do not have methods.
Java provides eight primitive data types: "byte", "short", "int", "long", "float", "double", "char", and "boolean".
Primitive data types are used to store simple values like "numbers", "characters", and "boolean" values.
8-bit signed integer
Size: 1 byte
defaultValue: 0
Range: -128 to 127
byte rollNo = 19;
16-bit signed integer
Size: 2 bytes
defaultValue: 0
Range: -32,768 to 32,767.
short seconds = 3600;
32-bit signed integer
Size: 4 bytes
defaultValue: 0
Range: -2^31 to 2^31 - 1.
int count = 1000;
64-bit signed integer
Size: 8 bytes
defaultValue: 0L
Range: -2^63 to 2^63 - 1.
long population = 10000000000L;
32-bit floating point
Size: 4 bytes
defaultValue: 0.0f
Range: ±3.4e-38 to ±3.4e+38.
float pi = 3.14f;
64-bit floating point
Size: 8 bytes
defaultValue: 0.0
Range: ±1.7e-308 to ±1.7e+308.
double price = 99.99;
16-bit Unicode character
Size: 2 bytes
defaultValue: '\u0000'
Range: '\u0000' to '\uffff'.
char alpha = 'A';
Represents true or false
Size: 1 bit
defaultValue: false
Size not precisely defined.
boolean isStudent = true;
Reference data types are used to refer to objects. They store references (memory addresses) to objects rather than the actual object data.
Reference data types include classes, interfaces, arrays, and enums.
Unlike primitive data types, reference data types can have methods and can be used to create complex data structures.
String greetingMsg = "Hello, world!"; // String is a reference data type