Java Data Types
Data types in Java define the type of data a variable can store. Java is a strongly typed language, which means you must specify the data type when declaring a variable.
Types of Data Types
Java has two main types of data types:
- Primitive Data Types
- Non-Primitive Data Types
Primitive Data Types
Primitive data types are the basic types built into Java.
int→ stores whole numbersdouble→ stores decimal numberschar→ stores a single characterboolean→ stores true or false
Example
public class Main {
public static void main(String[] args) {
int age = 25;
double price = 10.5;
char grade = 'A';
boolean isActive = true;
System.out.println(age);
System.out.println(price);
System.out.println(grade);
System.out.println(isActive);
}
}
Try this code
Non-Primitive Data Types
Non-primitive data types are more complex and are used to store collections or objects.
String→ stores textArray→ stores multiple valuesClass→ used to create objects
Example
public class Main {
public static void main(String[] args) {
String name = "Ali";
int[] numbers = {1, 2, 3};
System.out.println(name);
System.out.println(numbers[0]);
}
}
Try this code
Difference Between Primitive and Non-Primitive
- Primitive types store simple values
- Non-primitive types store references to objects
- Primitive types are faster
- Non-primitive types have methods and properties
Important Note
Each data type uses a different amount of memory. Choosing the correct data type helps improve performance.
Why Data Types are Important
- They define what kind of data can be stored
- They help prevent errors
- They improve program performance
- They make code more organized