What Are Data Types in Java: Explanation and Examples
data types specify the kind of data a variable can hold, such as numbers, text, or true/false values. They help the computer understand how much memory to allocate and what operations are allowed on the data.How It Works
Think of data types in Java like different containers for storing things. Just like you wouldn't put water in a box meant for books, Java uses data types to decide what kind of information a variable can hold. This helps the computer organize memory efficiently and avoid mistakes.
Java has two main groups of data types: primitive types like numbers and true/false values, and reference types like objects and arrays. Primitive types hold simple values directly, while reference types point to more complex data stored elsewhere.
Example
This example shows how to declare variables with different data types and print their values.
public class DataTypesExample { public static void main(String[] args) { int age = 25; // whole number double price = 19.99; // decimal number char grade = 'A'; // single character boolean isJavaFun = true; // true or false String name = "Alice"; // text (reference type) System.out.println("Age: " + age); System.out.println("Price: " + price); System.out.println("Grade: " + grade); System.out.println("Is Java fun? " + isJavaFun); System.out.println("Name: " + name); } }
When to Use
Use data types whenever you create variables to store information in your program. Choosing the right data type helps your program run efficiently and correctly. For example, use int for counting items, double for prices or measurements, boolean for yes/no decisions, and String for words or sentences.
In real life, if you are making a program to track a library, you might use int for the number of books, String for book titles, and boolean to check if a book is available.
Key Points
- Data types tell Java what kind of data a variable holds.
- Primitive types include
int,double,char, andboolean. Stringis a common reference type for text.- Choosing the right data type helps your program use memory well and avoid errors.