DEV Community

Kesavarthini
Kesavarthini

Posted on

Java Basics: Variables and Data Types Explained for Beginners

Hello everyone 👋
This is my Day 3 learning blog on Java programming.
As a beginner, I’m sharing what I learned about variables and data types in a simple and easy-to-understand way.

🔹 What is a Variable in Java?

A variable is a container used to store data values in a Java program.
• The value of a variable can change during program execution
• Each variable has a data type
• Java is a strongly typed language

Example:

int age = 20;
Enter fullscreen mode Exit fullscreen mode

Here, age is a variable that stores an integer value.

🔹 Why Do We Need Variables?
• To store data temporarily
• To reuse values in a program
• To make programs dynamic and flexible

🔹What are Data Types in Java?

Data types define the type of data a variable can store.

Java data types are mainly divided into:
• Primitive Data Types
• Non-Primitive Data Types

🔹 List of Primitive Data Types
ava primitive data types are:
1. byte
2. short
3. int
4. long
5. float
6. double
7. char
8. boolean

⸻

🔹 Integer Data Types

These data types are used to store whole numbers.

â–¶ byte
• Size: 1 byte
• Range: -128 to 127

byte b = 10;
Enter fullscreen mode Exit fullscreen mode

â–¶ short
• Size: 2 bytes

short s = 200;
Enter fullscreen mode Exit fullscreen mode

â–¶ int
• Size: 4 bytes
• Most commonly used

int number = 1000;
Enter fullscreen mode Exit fullscreen mode

â–¶ long
• Size: 8 bytes
• Use L at the end

long population = 9876543210L;
Enter fullscreen mode Exit fullscreen mode

🔹 Floating-Point Data Types

Used to store decimal values.

â–¶ float
• Size: 4 bytes
• Use f at the end

float marks = 85.5f;
Enter fullscreen mode Exit fullscreen mode

â–¶ double
• Size: 8 bytes
• More precise than float

double price = 99.99;
Enter fullscreen mode Exit fullscreen mode

🔹 Character Data Type

â–¶ char
• Size: 2 bytes
• Stores a single character

char grade = 'A';
Enter fullscreen mode Exit fullscreen mode

🔹 Boolean Data Type

â–¶ boolean
• Stores only true or false

boolean isPassed = true;
Enter fullscreen mode Exit fullscreen mode

🔹 Simple Example Program

public class Main {
    public static void main(String[] args) {
        int age = 21;
        float marks = 88.5f;
        char grade = 'A';
        boolean result = true;

        System.out.println(age);
        System.out.println(marks);
        System.out.println(grade);
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Non-Primitive Data Types
• String
• Arrays
• Classes
• Interfaces

Example:

String name = "Akalya";
Enter fullscreen mode Exit fullscreen mode

🔹 Key Difference: Variable vs Data Type
• Variable → Stores the value
• Data Type → Defines the type of value

Top comments (0)