DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 8 of 59
←PreviousPrevNextNext→

Java Variables - Complete Guide

Introduction to Variables

Variables in Java act as named containers for storing data. They allow programs to store, update, and retrieve values dynamically during execution.

Every variable in Java must have a declared data type that defines the kind of values it can hold, its memory size, and the operations that can be applied. Because Java is statically typed, variables must be declared before use.

Variable Declaration and Initialization

Declaring a variable means specifying its type and name. Initializing a variable assigns it an initial value. Declaration and initialization can be done separately or in one statement.

Example
public class VariableBasics {
    public static void main(String[] args) {
        // Declaration only
        int age;
        double salary;
        String name;

        // Initialization after declaration
        age = 25;
        salary = 50000.75;
        name = "John Doe";

        // Declaration and initialization together
        int score = 100;
        double temperature = 98.6;
        String greeting = "Hello, World!";

        // Multiple variables of same type
        int x = 10, y = 20, z = 30;

        // Constants using final
        final double PI = 3.14159;
        final int MAX_USERS = 1000;

        System.out.println("Name: " + name + ", Age: " + age + ", Salary: $" + salary);
    }
}
Output
Name: John Doe, Age: 25, Salary: $50000.75

Variable Types and Scope

Variables are classified by where they are declared and how long they live in memory:

Variable TypeDeclaration LocationScopeLifetime
Local VariablesInside methods/blocksWithin the blockDuring method execution
Instance VariablesInside class, outside methodsEach object instanceObject lifetime
Class Variables (static)Declared with static keywordShared across classUntil program ends
ParametersDeclared in method signatureWithin the methodDuring method execution

Data Types and Variables

Java variables are strictly typed and can be either primitive or reference types:

Example
public class DataTypesDemo {
    public static void main(String[] args) {
        // Primitive data types
        byte smallNumber = 100;         // 8-bit integer
        short mediumNumber = 10000;     // 16-bit integer
        int population = 1000000;       // 32-bit integer
        long bigNumber = 10000000000L;  // 64-bit integer (requires L)

        float price = 19.99f;           // 32-bit floating point (requires f)
        double preciseValue = 3.1415926535; // 64-bit floating point

        char grade = 'A';               // 16-bit Unicode character
        boolean isJavaFun = true;       // true or false

        // Reference data types
        String message = "Welcome to Java";
        int[] numbers = {1, 2, 3, 4, 5};

        System.out.println("Byte: " + smallNumber);
        System.out.println("Double: " + preciseValue);
        System.out.println("String: " + message);
    }
}
Output
Byte: 100
Double: 3.1415926535
String: Welcome to Java

Type Conversion and Casting

Java supports automatic type promotion (widening) and explicit type conversion (narrowing):

Example
public class TypeConversion {
    public static void main(String[] args) {
        // Implicit conversion (widening)
        int intValue = 100;
        long longValue = intValue;
        double doubleValue = intValue;

        // Explicit conversion (narrowing)
        double precise = 9.87;
        int approx = (int) precise; // decimal truncated

        byte smallByte = (byte) 200; // overflow risk

        // Char to int conversion
        char letter = 'A';
        int asciiValue = letter;

        System.out.println("Double: " + precise + ", Cast to int: " + approx);
        System.out.println("Char: " + letter + ", ASCII: " + asciiValue);
        System.out.println("Byte from 200: " + smallByte + " (overflow)");
    }
}
Output
Double: 9.87, Cast to int: 9
Char: A, ASCII: 65
Byte from 200: -56 (overflow)

Best Practices for Variables

  • ✅ Use descriptive variable names that reflect purpose
  • ✅ Initialize variables at declaration when possible
  • ✅ Use `final` for values that must remain constant
  • ✅ Choose the smallest suitable data type for efficiency
  • ✅ Be careful with narrowing casts to avoid unexpected results
  • ✅ Declare variables close to where they are used
  • ✅ Avoid magic numbers — replace with named constants
  • ✅ Follow Java naming conventions (camelCase for variables, UPPER_CASE for constants)
Test your knowledge: Java Variables - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 8 of 59
←PreviousPrevNextNext→