-->

Java Programming Step 2: Java Variables and Data Types | Complete Beginner's Guide

 Java Programming Step 2

Java Variables and Data Types




    Introduction

    Java Variables and Data Types are fundamental concepts that every Java programmer must understand. Variables allow you to store information in a program, while data types determine what kind of information can be stored.

    In this Step 2 Java Programming Tutorial, you will learn how to declare and initialize variables, understand Java's primitive and non-primitive data types, work with numbers and characters, use boolean values, understand type conversion, and apply variables in practical Java programs.

    If you have completed Step 1: Java Fundamentals, you are now ready to learn how Java stores and manages data.




    What You Will Learn

    After completing this lesson, you will understand:

    • What a variable is
    • Why variables are used
    • Variable declaration
    • Variable initialization
    • Declaration and initialization together
    • Java variable naming rules
    • Local variables
    • Instance variables
    • Static variables
    • Primitive data types
    • Non-primitive data types
    • Integer types
    • Floating-point types
    • Character type
    • Boolean type
    • Default values
    • Literals
    • Type casting
    • Widening conversion
    • Narrowing conversion
    • var and local variable type inference
    • Constants using final
    • Practical examples
    • Practice exercises
    • Mini project




    What Is a Variable in Java?

    A variable is a named location used to store a value in a Java program.

    For example:

    int age = 20;

    Here:

    • int is the data type.
    • age is the variable name.
    • 20 is the value stored in the variable.
    • = is the assignment operator.

    You can later assign another value to the variable:

    age = 25;

    The variable now contains 25.




    Why Are Variables Important?

    Variables allow programs to work with changing information.

    For example, instead of writing:

    System.out.println(20);

    you can store the value:

    int age = 20;
    
    System.out.println(age);

    This makes your program easier to understand and modify.

    Variables can store information such as:

    • Student names
    • Ages
    • Prices
    • Marks
    • Quantities
    • Account balances
    • Boolean conditions
    • Characters
    • Calculated results




    Variable Declaration

    Variable declaration tells Java the variable's data type and name.

    Syntax:

    dataType variableName;

    Example:

    int age;
    double price;
    String name;
    boolean student;

    At this point, the variables have been declared.




    Variable Initialization

    Initialization means assigning an initial value to a variable.

    Example:

    int age = 20;

    Here, the variable age is declared and initialized at the same time.

    Another example:

    int age;
    
    age = 20;

    The first statement declares the variable, while the second assigns its value.




    Declaration and Initialization Together

    You can usually declare and initialize a variable in a single statement.

    int age = 20;
    double salary = 50000.50;
    String name = "Rahim";
    boolean active = true;

    This is one of the most common ways to create variables in Java.




    Changing Variable Values

    Variables can normally be reassigned.

    int score = 50;
    
    System.out.println(score);
    
    score = 80;
    
    System.out.println(score);

    Output:

    50
    80

    The variable score initially contains 50 and is later changed to 80.




    Java Variable Naming Rules

    Java has rules for naming variables.

    A variable name:

    • Can contain letters.
    • Can contain digits.
    • Can contain _.
    • Can contain $.
    • Cannot normally begin with a digit.
    • Cannot contain spaces.
    • Cannot be a reserved Java keyword.
    • Is case-sensitive.

    Valid Examples

    int age;
    int studentAge;
    int total_marks;
    int number1;
    String firstName;

    Invalid Examples

    int 1number;
    int student age;
    int class;

    The first begins with a digit, the second contains a space, and class is a Java keyword.




    Java Naming Conventions

    Java developers generally use camelCase for variable names.

    Good examples:

    studentName
    totalMarks
    accountBalance
    phoneNumber
    dateOfBirth

    Avoid unclear names such as:

    x
    abc
    n1
    data123

    when a more descriptive name is possible.

    Good variable names make code easier to understand.




    Types of Variables in Java

    Java variables can be categorized according to where they are declared and how they belong to objects or classes.

    The commonly discussed categories are:

    1. Local variables
    2. Instance variables
    3. Static variables

    Local Variables

    A local variable is declared inside a method, constructor, or block.

    Example:

    public class Main {
    
        public static void main(String[] args) {
    
            int age = 20;
    
            System.out.println(age);
        }
    }

    Here, age is a local variable.

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

    Instance Variables

    An instance variable is declared inside a class but outside methods, constructors, or blocks, without being declared static.

    Each object can have its own copy.

    Example:

    class Student {
    
        String name;
        int age;
    }

    Here, name and age are instance variables.

    Static Variables

    A static variable belongs to the class rather than to individual objects.

    It is declared using the static keyword.

    Example:

    class Student {
    
        static String schoolName = "ABC School";
    }

    The static variable can be accessed through the class:

    System.out.println(Student.schoolName);

    Static members are associated with the class itself.




    What Are Data Types?

    A data type specifies the kind of value that a variable can store.

    For example:

    int age = 20;

    The int data type tells Java that age is intended to store an integer value.

    Java data types are broadly divided into:

    1. Primitive Data Types

    Java has eight primitive data types:

    byte
    short
    int
    long
    float
    double
    char
    boolean

    2. Reference Types

    Examples include:

    String
    Arrays
    Classes
    Interfaces
    Enums
    Records

    Reference variables hold references to objects rather than storing object data directly in the variable itself.



    Java Primitive Data Types

    Let's look at the eight primitive data types.

    Data TypeGeneral Purpose
    byteSmall integer
    shortInteger larger than byte
    intGeneral-purpose integer
    longLarge integer
    floatSingle-precision decimal
    doubleDouble-precision decimal
    charSingle UTF-16 code unit
    booleantrue or false

    byte Data Type

    The byte type uses 8 bits and represents signed integer values from:

    -128 to 127

    Example:

    byte age = 25;

    It can be useful when working with raw binary data or when memory efficiency matters for large collections of numeric values.

    short Data Type

    The short type uses 16 bits and represents signed integer values from:

    -32,768 to 32,767

    Example:

    short temperature = 250;

    For general integer calculations, int is usually preferred.

    int Data Type

    The int type uses 32 bits and is the most commonly used integer type in Java.

    Its range is:

    -2,147,483,648 to 2,147,483,647

    Example:

    int age = 25;
    int marks = 95;
    int population = 1000000;

    For most ordinary whole-number calculations, int is the natural choice.

    long Data Type

    The long type uses 64 bits and stores larger integer values.

    Example:

    long population = 170000000L;

    The L suffix explicitly identifies the literal as a long.

    Example:

    long distance = 9000000000L;

    Without an appropriate suffix, a large integer literal may be treated as an int literal and fail to compile if it exceeds the int range.

    float Data Type

    The float type represents single-precision floating-point values.

    Example:

    float price = 99.50f;

    The f suffix is normally required because decimal literals are double by default.

    float temperature = 36.5f;

    For many general-purpose calculations, double is preferred because it provides greater precision.

    double Data Type

    The double type represents double-precision floating-point values.

    Example:

    double price = 99.99;
    double pi = 3.141592653589793;

    A decimal literal such as:

    99.99

    is a double literal by default.

    char Data Type

    The char type represents a single UTF-16 code unit.

    Character values are written using single quotes.

    Example:

    char grade = 'A';
    char letter = 'J';

    This is different from a String:

    String name = "Jitu";

    A char holds one UTF-16 code unit, while a String represents a sequence of characters.

    boolean Data Type

    The boolean type stores one of two values:

    true
    false

    Example:

    boolean isStudent = true;
    boolean isLoggedIn = false;

    Booleans are commonly used in conditions and decision-making.

    Example:

    boolean isAdult = true;
    
    if (isAdult) {
        System.out.println("Adult");
    }




    String in Java

    String is not a primitive data type. It is a class in Java.

    Example:

    String name = "Jitu";

    You can use strings to store text.

    String message = "Welcome to Java Programming";

    Strings provide many useful methods, such as:

    length()
    toUpperCase()
    toLowerCase()
    substring()
    contains()
    equals()
    replace()

    We will study Strings in greater detail in a later lesson.




    Java Data Type Example

    Let's use several data types in one program.

    public class Main {
    
        public static void main(String[] args) {
    
            byte smallNumber = 100;
            short shortNumber = 1000;
            int age = 25;
            long population = 170000000L;
    
            float price = 99.50f;
            double pi = 3.141592653589793;
    
            char grade = 'A';
            boolean passed = true;
    
            String name = "Jitu";
    
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Grade: " + grade);
            System.out.println("Passed: " + passed);
            System.out.println("Price: " + price);
        }
    }




    Primitive vs Reference Types

    One important distinction is between primitive types and reference types.

    Primitive Example

    int age = 20;

    age directly holds a primitive value.

    Reference Example

    String name = "Jitu";

    name is a reference variable associated with a String object.

    Arrays are also reference types:

    int[] numbers = {10, 20, 30};

    Understanding this distinction becomes increasingly important when you study objects, classes, arrays, and memory behavior.




    Default Values

    Instance variables and static variables receive default values if you do not explicitly initialize them.

    Examples of default values include:

    TypeDefault Value
    byte    0
    short    0
    int    0
    long    0L
    float    0.0f
    double    0.0d
    char   '\u0000'
    boolean   false
    Reference types   null

    Example:

    class Student {
    
        int age;
        boolean active;
        String name;
    }

    These fields receive their default values when an object is created.

    Important

    Local variables do not automatically receive these default values.

    This will not compile:

    public static void main(String[] args) {
    
        int age;
    
        System.out.println(age);
    }

    You must initialize the local variable first:

    int age = 20;
    
    System.out.println(age);




    Java Literals

    A literal is a fixed value written directly in source code.

    Examples:

    100
    3.14
    'A'
    true
    "Java"

    Different literal types include:

    • Integer literals
    • Floating-point literals
    • Character literals
    • String literals
    • Boolean literals
    • null reference literal

    Example:

    int number = 100;
    double price = 50.5;
    char grade = 'A';
    boolean result = true;
    String language = "Java";

    Integer Literals

    Java supports several integer literal forms.

    Decimal

    int number = 100;

    Binary

    Binary literals use the 0b or 0B prefix.

    int number = 0b1010;

    Octal

    Octal literals begin with 0.

    int number = 012;

    Hexadecimal

    Hexadecimal literals use the 0x or 0X prefix.

    int number = 0xFF;

    These forms can be useful when working with low-level data and bit operations.




    Underscores in Numeric Literals

    Java allows underscores inside numeric literals to improve readability.

    Example:

    int population = 170_000_000;
    long distance = 9_000_000_000L;

    The underscores are ignored by the compiler.

    This:

    170_000_000

    represents the same numeric value as:

    170000000



    Type Casting in Java

    Type casting means converting a value from one data type to another compatible type.

    There are two major forms:

    1. Widening conversion
    2. Narrowing conversion

    Widening Conversion

    Widening conversion occurs when a value is converted from a type with a smaller range or precision to a compatible type with a larger range or precision.

    Example:

    int number = 100;
    
    double value = number;
    
    System.out.println(value);

    Output:

    100.0

    Java can perform this conversion automatically.

    A common numeric widening sequence is:

    byte → short → int → long → float → double

    char can also participate in numeric conversions, but its conversion relationships should be considered separately.

    Narrowing Conversion

    Narrowing conversion occurs when converting to a type that cannot represent all values of the original type.

    It generally requires an explicit cast.

    Example:

    double price = 99.99;
    
    int value = (int) price;
    
    System.out.println(value);

    Output:

    99

    The fractional portion is discarded.

    Important

    Narrowing conversions can result in:

    • Loss of fractional information
    • Overflow or underflow
    • Changes in numerical value

    Therefore, use explicit casts carefully.

    Type Casting Example

    public class Main {
    
        public static void main(String[] args) {
    
            int number = 100;
    
            double decimalNumber = number;
    
            System.out.println("Widening: " + decimalNumber);
    
            double price = 99.99;
    
            int wholeNumber = (int) price;
    
            System.out.println("Narrowing: " + wholeNumber);
        }
    }

    Output:

    Widening: 100.0
    Narrowing: 99



    Integer Division

    Be careful when performing division between integer values.

    Example:

    int a = 10;
    int b = 3;
    
    int result = a / b;
    
    System.out.println(result);

    Output:

    3

    The result is an integer because both operands are integers.

    If you want a decimal result:

    double result = (double) a / b;
    
    System.out.println(result);

    This produces approximately:

    3.3333333333333335



    Constants in Java

    A constant is a variable whose value cannot be reassigned after initialization.

    Java uses the final keyword.

    Example:

    final double PI = 3.14159;

    You cannot later write:

    PI = 3.14;

    because PI is final.

    Constants are commonly written using uppercase letters and underscores:

    final int MAX_USERS = 100;
    final double TAX_RATE = 0.15;



    The var Keyword

    Java supports local variable type inference using var.

    Example:

    var age = 25;
    var name = "Jitu";
    var price = 99.99;

    Java determines the variable's type from its initializer.

    For example:

    var age = 25;

    is inferred as:

    int

    Important Rules

    var:

    • Can be used for local variables.
    • Requires an initializer.
    • Is not a dynamically typed variable.
    • Cannot normally be used for fields.
    • Cannot be used for method parameters in ordinary declarations.
    • Cannot be initialized with null because Java cannot infer a type from null alone.

    Example:

    var age = 20;

    is valid.

    But:

    var age;

    is invalid because there is no initializer.

    For beginners, explicit types such as int, double, and String are often easier to understand.




    Variable Scope

    Scope describes where a variable can be accessed.

    Example:

    public class Main {
    
        public static void main(String[] args) {
    
            int age = 20;
    
            if (age >= 18) {
    
                String message = "Adult";
    
                System.out.println(message);
            }
        }
    }

    The variable message exists within the if block.

    Trying to access it outside that block would cause a compilation error.

    Understanding scope is important when writing larger programs.




    Variable Lifetime

    The lifetime of a variable refers to how long the variable remains available during program execution.

    Local variables are associated with their method or block execution.

    Instance variables exist as part of an object.

    Static variables are associated with the class and are shared according to the class's lifecycle.

    These concepts become more important when you learn OOP and memory management.




    Practical Example – Student Information

    Let's create a practical Java program using variables and different data types.

    public class Main {
    
        public static void main(String[] args) {
    
            String studentName = "Rahim";
            int age = 20;
            double cgpa = 3.75;
            char grade = 'A';
            boolean passed = true;
    
            System.out.println("===== Student Information =====");
            System.out.println("Name: " + studentName);
            System.out.println("Age: " + age);
            System.out.println("CGPA: " + cgpa);
            System.out.println("Grade: " + grade);
            System.out.println("Passed: " + passed);
        }
    }

    Output:

    ===== Student Information =====
    Name: Rahim
    Age: 20
    CGPA: 3.75
    Grade: A
    Passed: true

    This example demonstrates how different types of information can be stored in variables.




    Practical Example – Product Information

    public class Main {
    
        public static void main(String[] args) {
    
            String productName = "Laptop";
            double price = 75000.00;
            int quantity = 2;
            boolean available = true;
    
            double total = price * quantity;
    
            System.out.println("===== Product Information =====");
            System.out.println("Product: " + productName);
            System.out.println("Price: " + price);
            System.out.println("Quantity: " + quantity);
            System.out.println("Available: " + available);
            System.out.println("Total: " + total);
        }
    }




    Common Mistakes with Variables and Data Types

    Mistake 1: Using an Uninitialized Local Variable

    Incorrect:

    int age;
    
    System.out.println(age);

    Correct:

    int age = 20;
    
    System.out.println(age);


    Mistake 2: Assigning an Incompatible Value

    Incorrect:

    int age = "20";

    Correct:

    int age = 20;


    Mistake 3: Forgetting the f Suffix

    This is invalid:

    float price = 10.5;

    Use:

    float price = 10.5f;


    Mistake 4: Forgetting L for Large Long Literals

    Use:

    long population = 170000000L;

    The L makes the intended long literal explicit.


    Mistake 5: Unexpected Integer Division

    int result = 5 / 2;

    The result is:

    2

    For a decimal result:

    double result = 5.0 / 2;

    The result is:

    2.5




    Practice Exercises

    Now test your understanding.

    Exercise 1 – Personal Information

    Create variables for:

    • Name
    • Age
    • Country
    • Height
    • Student status

    Print all values.

    Exercise 2 – Product Calculation

    Create:

    productName
    price
    quantity

    Calculate:

    total = price × quantity

    Print the result.

    Exercise 3 – Temperature

    Create a Celsius temperature variable and convert it to Fahrenheit.

    Formula:

    F = (C × 9 / 5) + 32

    Exercise 4 – Type Casting

    Create a double variable:

    double number = 45.75;

    Convert it to int and print the result.

    Exercise 5 – Student Result

    Create variables for:

    studentName
    marks
    grade
    passed

    Display all information.


    Challenge Exercise

    Create a Java program for an employee profile.

    Store:

    • Employee name
    • Employee ID
    • Age
    • Salary
    • Department
    • Employment status

    Example output:

    ==============================
          EMPLOYEE PROFILE
    ==============================
    Name: Rahim Hasan
    ID: 1001
    Age: 25
    Salary: 45000.0
    Department: IT
    Active: true
    ==============================

    Try to create the program without looking at the previous examples.




    Mini Project – Simple Shopping Bill

    Let's combine variables, data types, arithmetic, and output.

    public class Main {
    
        public static void main(String[] args) {
    
            String productName = "Keyboard";
    
            double price = 1200.00;
            int quantity = 2;
    
            double subtotal = price * quantity;
            double discount = 100.00;
            double total = subtotal - discount;
    
            System.out.println("==============================");
            System.out.println("        SHOPPING BILL");
            System.out.println("==============================");
    
            System.out.println("Product: " + productName);
            System.out.println("Price: " + price);
            System.out.println("Quantity: " + quantity);
            System.out.println("Subtotal: " + subtotal);
            System.out.println("Discount: " + discount);
            System.out.println("Total: " + total);
    
            System.out.println("==============================");
        }
    }

    Expected Output

    ==============================
            SHOPPING BILL
    ==============================
    Product: Keyboard
    Price: 1200.0
    Quantity: 2
    Subtotal: 2400.0
    Discount: 100.0
    Total: 2300.0
    ==============================

    This mini project gives you practical experience with:

    • Variables
    • String
    • double
    • int
    • Arithmetic expressions
    • Assignment
    • Output
    • Basic program structure



    Quick Revision

    ConceptKey Point
    Variable            Named storage for a value
    Data Type            Defines the kind of value
    byte            8-bit signed integer
    short           16-bit signed integer
    int           32-bit signed integer
    long           64-bit signed integer
    float           Single-precision floating point
    double           Double-precision floating point
    char           Single UTF-16 code unit
    boolean      true or false
    String           Reference type for text
    final           Prevents reassignment
    var           Local variable type inference
    Casting          Converting between compatible types
    Local Variable          Declared inside a method/block
    Instance Variable          Non-static field belonging to an object
    Static Variable          Class-associated field



    What You Should Know Before Step 3

    Before continuing to the next lesson, make sure you can:

    • Explain what a variable is.
    • Declare and initialize variables.
    • Change variable values.
    • Follow Java variable naming rules.
    • Understand local, instance, and static variables.
    • Explain primitive data types.
    • Explain reference types.
    • Use int, long, float, double, char, and boolean.
    • Understand how String differs from primitive types.
    • Use numeric literals.
    • Understand default values for fields.
    • Explain why local variables must be initialized before use.
    • Perform widening conversions.
    • Perform explicit narrowing casts.
    • Understand integer division.
    • Create constants using final.
    • Understand basic use of var.
    • Solve the practice exercises.



    Conclusion

    Java Variables and Data Types are essential building blocks of Java programming. Variables allow your programs to store and manipulate information, while data types tell Java what kind of values those variables can represent.

    You have now learned Java's eight primitive data types, reference types, variable declaration and initialization, variable scope, constants, literals, type conversion, casting, and practical programming examples.

    The next step is to learn how Java performs calculations and comparisons.


    Next Lesson

    Step 3: Java Operators – Arithmetic, Relational, Logical, Assignment and More

    In the next lesson, you will learn how to perform calculations, compare values, combine conditions, assign values, and build expressions in Java.



    Frequently Asked Questions (FAQ)

    What is a variable in Java?
    A variable is a named storage location used to hold a value in a Java program. A variable has a declared type and can normally be assigned a new value during program execution.
    What are the primitive data types in Java?
    Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean.
    Is String a primitive data type in Java?
    No. String is a reference type in Java. It is a class used to represent sequences of characters.
    What is type casting in Java?
    Type casting is the conversion of a value from one compatible data type to another. Widening conversions can often happen automatically, while narrowing conversions generally require an explicit cast.
    What is the difference between int and double in Java?
    The int type is used for whole-number values, while double is used for double-precision floating-point values and can represent fractional numbers.
    What is the var keyword in Java?
    var enables local variable type inference. The compiler determines the variable's type from its initializer. It is still statically typed and is not a dynamically typed variable.
    What is a constant in Java?
    A constant is a variable that cannot be reassigned after initialization. Java commonly uses the final keyword to create constants.
    What is the difference between local, instance, and static variables?
    Local variables are declared inside methods or blocks, instance variables are non-static fields associated with objects, and static variables are class-associated fields shared according to the class's static member semantics.

    0/Post a Comment/Comments

    Thank You For Visit My Website.
    I Will Contact As Soon As Possible.