Java Variables

Learn everything about Java variables including declaration, initialization, data types, default values, examples, rules, and best practices.

What are Variables in Java?

Variables are containers used to store data values in Java. They help programs save and manipulate information.

Variables can store numbers, text, decimal values, and true/false values.

Variable Declaration

Variables are declared using a data type followed by a variable name.

int age;

String name;

double salary;

Variable Initialization

Assigning a value to a variable is called initialization.

int age = 25;

String name = "Alex";

double salary = 55000.50;

Printing Variables

public class Main {

    public static void main(String[] args) {

        int age = 25;

        System.out.println(age);

    }

}

Output

25

Java Variable Data Types

Every variable in Java must have a data type.

Data Type Description Example
int Integer numbers 10
double Decimal numbers 10.5
char Single character 'A'
boolean true or false true
String Text values "Hello"

Variable Examples

int marks = 90;

double price = 99.99;

char grade = 'A';

boolean isJavaEasy = true;

String city = "Delhi";

Changing Variable Values

int number = 10;

number = 50;

System.out.println(number);

Output

50

Final Variables

Variables declared with final cannot be changed.

final int speed = 100;

speed = 200;

The above code generates error because final variables cannot be reassigned.

Variable Naming Rules

Valid and Invalid Variable Names

Valid Variable Names

int age;

double totalPrice;

String studentName;

Invalid Variable Names

int 1age;

double total-price;

String class;

Java Naming Convention

Java developers usually follow camelCase naming convention.

int studentAge;

double totalSalary;

String firstName;

Default Values

Instance and static variables get default values automatically.

Data Type Default Value
int 0
double 0.0
boolean false
String null

Complete Java Variable Program

public class Student {

    public static void main(String[] args) {

        String name = "Alex";

        int age = 20;

        double marks = 89.5;

        boolean passed = true;

        System.out.println(name);

        System.out.println(age);

        System.out.println(marks);

        System.out.println(passed);

    }

}

Output

Alex
20
89.5
true

Common Variable Errors

Best Practices

Conclusion

Variables are one of the most important concepts in Java programming. They help programs store and manipulate data efficiently.

Understanding variables properly is essential before learning operators, conditions, loops, arrays, and object-oriented programming.