Data-Types
Programming data types define the kind of data a variable can hold. They determine the operations that can be performed on the data and how it is stored in memory.
In Java, data types are divided into two main categories:
- Primitive Data Types
- Reference Data Types
Primitive Data Types
Primitive data types are predefined by the language and named by a keyword. They are the most basic data types available within the Java language.There are eight primitive data types in Java:
Data Type | Size | Default Value | Range / Values |
---|---|---|---|
boolean | ~1 byte | false | true or false |
byte | 1 byte | 0 | -128 to 127 |
short | 2 bytes | 0 | -32,768 to 32767 |
int | 4 bytes | 0 |
-2^31 to 2^31-1 |
long | 8 bytes | 0L |
-2^63 to 2^63-1
|
float | 4 bytes | 0.0f | Up to 7 decimal places |
double | 8 bytes | 0.0d | Up to 15 decimal places |
char | 2 bytes | '\u0000' | unicode characters (0 to 65,535) |
Reference Data Types
Reference types in Java are any objects created from classes.
They are used to access objects and include:
- Class Objects: Instances of classes, e.g.,
String
,Scanner
. - Array: Objects that store multiple items of the same type.
- Interface: Defines a contract that classes can implement.
- Enumeration: A special Java type used to define collections of constants.
Key Differences Between Primitive and Reference Data Types:
- Memory: Primitive data types are stored directly in the memory locations allocated for variables, while reference types store references (or addresses) to the objects in memory.
- Default Values: Primitive data types have default values (e.g.,
0
for integers,false
for boolean). Reference types have a default value ofnull
. - Methods: Primitive data types do not have methods associated with them, whereas objects of reference types do.
Examples:
Here's a basic example to illustrate the use of primitive and reference data types:
public class DataTypesExample {
public static void main(String[] args) {
// Primitive data types
int age = 25;
char grade = 'A';
boolean isJavaFun = true;
double price = 19.99;
// Reference data types
String name = "John";
int[] scores = {90, 85, 88};
// Output
System.out.println("Age: " + age);
System.out.println("Grade: " + grade);
System.out.println("Is Java Fun: " + isJavaFun);
System.out.println("Price: " + price);
System.out.println("Name: " + name);
System.out.print("Scores: ");
for (int score : scores) {
System.out.print(score + " ");
}
}
}
In this example:
int
,char
,boolean
, anddouble
are primitive data types.String
andint[]
(array of integers) are reference data types.