When you start learning Java, one of the first things you come across is datatypes. At first, it may seem like just syntax, but it actually plays a very important role in how your program works.
What is a Datatype?
A datatype in Java defines what kind of value a variable can store.
In simple terms, it tells the computer whether the data is a number, a character, or something else.
For example:
int age = 25;
Here, int is the datatype, and it tells Java that the variable age will store a number.
Types of Datatypes in Java
Java datatypes are mainly divided into two categories:
1. Primitive Datatypes
Primitive datatypes are the most basic types in Java. They store simple values directly.
There are 8 primitive datatypes:
Integer Types
These are used to store whole numbers.
-
byte– for small numbers -
short– for slightly larger values -
int– most commonly used -
long– for very large numbers
Example:
int marks = 90;
long distance = 100000L;
Decimal Types
Used for numbers with decimal points.
-
float– less precision -
double– more precision (commonly used)
Example:
float price = 99.5f;
double pi = 3.14159;
Character Type
Used to store a single character.
char grade = 'A';
Boolean Type
Used to store true or false values.
boolean isPassed = true;
2. Non-Primitive Datatypes
Non-primitive datatypes are more complex. Instead of storing the actual value, they store a reference to the value.
String
Used to store text.
String name = "John";
Array
Used to store multiple values in a single variable.
int[] marks = {85, 90, 78};
Class and Object
These are used to create real-world models like Student, Car, etc.
Key Differences
| Primitive Datatypes | Non-Primitive Datatypes |
|---|---|
| Store actual values | Store references |
| Fixed size | Flexible size |
| Faster performance | Slightly slower |
Easy Way to Understand
Think of it like this:
- Primitive datatype → stores the actual value
- Non-primitive datatype → stores the address of the value
Conclusion
Datatypes are the foundation of Java programming.
They help define what kind of data you are working with and ensure your program runs correctly.
Choosing the right datatype makes your code more efficient and easier to understand.