Java Tutorial 0/145 lessons ~6 min read Lesson 9

    Variables & Data Types

    java variables data types primitive int double boolean char long float byte short string var type inference widening conversion

    Course progress0%
    Focus
    25 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Every application works with data.

    A banking system stores account balances.

    An e-commerce website stores product prices.

    A school management system stores student information.

    A social media application stores usernames, posts, and comments.

    But where does Java store all this information while a program is running?

    The answer is variables.

    A variable is a named memory location that stores data. Every variable has a data type, which tells Java what kind of data it can store and how much memory should be allocated.

    Choosing the correct data type improves:

    • Performance
    • Memory usage
    • Code readability
    • Program reliability

    In this lesson, you'll learn how variables work, how Java stores different kinds of data, and how to choose the right data type for real-world applications.

    What is a Variable?

    A variable is a named container that holds a value.

    Think of a variable as a labeled storage box.

    For example:

    Name → Rahul
    Age → 25
    Salary → 50000

    Here:

    • Name
    • Age
    • Salary

    are variables.

    Their values can change while the program is running.

    Declaring a Variable

    Before using a variable, Java requires you to declare it.

    Syntax:

    java
    dataType variableName;

    Example:

    java
    int age;

    Here:

    • int is the data type.
    • age is the variable name.

    At this point, the variable exists but has not been assigned a value.

    Initializing a Variable

    Initialization means assigning a value to a variable.

    Example:

    java
    int age = 25;

    Now:

    • Data Type → int
    • Variable Name → age
    • Value → 25

    Declaring Multiple Variables

    You can declare multiple variables of the same type in one statement.

    java
    int width = 10, height = 20, length = 30;

    Although valid, avoid declaring too many variables on one line if it reduces readability.

    Variable Naming Rules

    A variable name:

    • Can contain letters, digits, _, and $
    • Cannot begin with a number
    • Cannot contain spaces
    • Cannot use Java keywords
    • Is case-sensitive

    Valid:

    studentName
    employeeId
    totalMarks

    Invalid:

    2name
    student name
    class

    Java Data Types

    Java data types are divided into two main categories.

    Data Types
    ├── Primitive
    └── Non-Primitive

    Let's understand both.

    Primitive Data Types

    Primitive data types store simple values directly.

    Java provides 8 primitive data types.

    Data TypeSizeExampleDefault Value*
    byte1 byte1000
    short2 bytes20000
    int4 bytes500000
    long8 bytes9000000000L0L
    float4 bytes12.5F0.0f
    double8 bytes99.990.0d
    char2 bytes'A''\u0000'
    booleanJVM-dependenttruefalse

    *These default values apply to instance and static fields, not local variables.

    Integer Types

    byte

    Range:

    -128 to 127

    Example:

    java
    byte age = 25;

    Useful when memory is limited.

    short

    Example:

    java
    short year = 2026;

    Less commonly used in everyday applications.

    int

    The most commonly used integer type.

    Example:

    java
    int salary = 75000;

    Use int unless you have a specific reason to choose another integer type.

    long

    Used for very large numbers.

    Example:

    java
    long population = 1400000000L;

    Notice the L suffix.

    Without it, Java treats the number as an int.

    Floating-Point Types

    float

    Example:

    java
    float temperature = 36.5F;

    The F suffix is required.

    double

    More precise than float.

    Example:

    java
    double price = 1999.99;

    Most Java applications use double for decimal values unless a different precision requirement exists.

    Note: For financial calculations involving currency, double can introduce rounding errors because of binary floating-point representation. Professional applications often use BigDecimal for precise monetary calculations. You'll learn about this later in the course.

    Character Type

    A char stores a single Unicode character.

    Example:

    java
    char grade = 'A';

    Notice: Characters use single quotes.

    Boolean Type

    A boolean stores only two values:

    true
    false

    Example:

    java
    boolean isLoggedIn = true;

    Booleans are commonly used in decision-making.

    Non-Primitive Data Types

    Non-primitive data types store references to objects.

    Examples include:

    • String
    • Arrays
    • Classes
    • Interfaces
    • Enums
    • Records
    • Collections

    Example:

    java
    String name = "Rahul";

    Unlike primitive types, String is an object.

    Primitive vs Non-Primitive

    PrimitiveNon-Primitive
    Stores value directlyStores a reference to an object
    Fixed sizeSize depends on the object
    Lowercase keywordsUsually class names (PascalCase)
    Faster for simple valuesCan provide methods and behavior

    Type Inference with `var`

    Starting with Java 10, you can use var for local variables.

    Example:

    java
    var name = "Rahul";
    var age = 25;

    The compiler infers the type.

    Equivalent to:

    java
    String name = "Rahul";
    int age = 25;

    When to Use `var`

    Use var when the type is obvious and improves readability.

    Avoid it if it makes the code harder to understand.

    Variable Assignment

    Variables can change.

    Example:

    java
    int score = 80;
    score = 90;
    System.out.println(score);

    Output:

    90

    The old value is replaced by the new one.

    Real-World Example

    Imagine an employee management system.

    java
    String employeeName = "Rahul";
    int employeeId = 101;
    double salary = 65000.50;
    boolean active = true;

    Each variable stores a different type of information.

    Choosing the correct data type makes the application efficient and easier to understand.

    Memory Representation

    When you write:

    java
    int age = 25;

    Conceptually:

    Variable
    age
    Value
    25

    For a reference type:

    java
    String name = "Rahul";

    Conceptually:

    Reference Variable
    name
    String Object
    "Rahul"

    The reference points to the object rather than storing the object itself.

    Type Conversion

    Java can automatically convert smaller numeric types to larger ones.

    Example:

    java
    int age = 25;
    double value = age;

    Output:

    25.0

    This is called widening conversion.

    Converting larger types to smaller ones requires explicit casting, which you'll learn in a later lesson.

    Best Practices

    Choose the Correct Data Type

    Use the smallest appropriate type only when it genuinely improves your design.

    In most applications:

    • int is the standard integer type.
    • double is commonly used for decimal values.
    • boolean is used for conditions.
    • String stores text.

    Use Meaningful Variable Names

    Bad:

    java
    int x;

    Better:

    java
    int employeeAge;

    Descriptive names improve readability.

    Initialize Variables Before Use

    Local variables must be assigned a value before they are read.

    Example:

    java
    int total;
    total = 100;

    Use Constants for Fixed Values

    If a value never changes, use a constant instead of a regular variable.

    You'll learn constants in an upcoming lesson.

    Avoid Overusing `var`

    var is convenient, but clarity should always come first.

    If the inferred type isn't obvious, declare the type explicitly.

    Common Mistakes

    Forgetting the L Suffix

    Incorrect:

    java
    long population = 1400000000;

    If the literal exceeds the int range, append L:

    java
    long population = 5000000000L;

    Forgetting the F Suffix

    Incorrect:

    java
    float price = 12.5;

    Correct:

    java
    float price = 12.5F;

    Using Double Quotes for Characters

    Incorrect:

    java
    char grade = "A";

    Correct:

    java
    char grade = 'A';

    Using Variables Before Initialization

    java
    int total;
    System.out.println(total);

    Local variables must be initialized before use.

    Choosing the Wrong Data Type

    Using double for financial calculations can lead to precision issues.

    For money, prefer dedicated types such as BigDecimal in professional applications.

    Hands-on Exercise

    Create a Java program that:

    1. Declares variables for:
      • Student name
      • Student age
      • Student ID
      • Percentage
      • Grade
      • IsPassed
    2. Prints all values.
    3. Updates the percentage and prints the new value.
    4. Uses var for a local variable where appropriate.
    5. Demonstrates automatic widening conversion from int to double.

    Try completing the exercise without copying the examples directly.

    Summary

    Variables allow Java programs to store and manipulate data during execution.

    Primitive data types store simple values directly, while non-primitive types store references to objects.

    Choosing appropriate data types, following naming conventions, and writing readable code are essential habits for every Java developer.

    As you continue learning Java, variables and data types will form the foundation for classes, methods, collections, databases, and enterprise applications.

    Key Takeaways

    • Variables store data in memory.
    • Every variable must have a data type.
    • Java provides eight primitive data types.
    • Non-primitive types include String, arrays, classes, and more.
    • Use meaningful variable names.
    • Initialize local variables before using them.
    • Use var thoughtfully for local variables when it improves readability.
    • Select data types based on the nature of the data, not habit.

    Professional Interview Questions

    1What is the difference between primitive and non-primitive data types?

    Professional Answer

    Primitive data types store values directly and have a fixed size. Non-primitive data types store references to objects and can contain both data and methods. Examples of primitive types include int and boolean, while String and arrays are non-primitive types.

    Follow-up Questions

    • Why is String not a primitive type?
    • Where are primitive values and object references stored?

    Interview Tip: Explain both the storage concept and provide examples to demonstrate a complete understanding.

    2What is the difference between float and double?

    Professional Answer

    Both represent floating-point numbers, but double provides greater precision and is the default choice for decimal values in Java. float uses less memory but requires the F suffix when assigning literals.

    Follow-up Questions

    • Why does float require the F suffix?
    • When would you choose float instead of double?

    Interview Tip: Mention that financial calculations often use BigDecimal instead of either type to avoid precision issues.

    3What is var in Java?

    Professional Answer

    var enables local variable type inference. The compiler determines the variable's type based on the assigned value. It can only be used for local variables that are initialized during declaration.

    Follow-up Questions

    • Can var be used for fields?
    • Can var be initialized with null?

    Interview Tip: Emphasize that var does not make Java dynamically typed—the inferred type is fixed at compile time.

    Ready to mark this lesson complete?Track your journey across the entire course.