Web Analytics

Java Variables

Beginner ~25 min read

A variable is like a container that holds data values. In Java, every variable has a specific type (which determines what kind of data it can hold) and a name (how you refer to it). Understanding how to declare, initialize, and manage variables is the first step to becoming a Java developer.

Declaration & Initialization

To use a variable in Java, you must first declared it and then initialize it with a value.

// Syntax: Type variableName = value;
int age = 25;

There are three ways to do this:

  1. Declaration only: int score; (Allocates memory)
  2. Initialization: score = 100; (Assigns value)
  3. Both together: int score = 100; (Most common)
Output
Click Run to execute your code

Variable Naming Rules

Java enforces strict rules for naming variables (identifiers):

  • Must start with a letter, underscore (_), or dollar sign ($).
  • Cannot start with a digit.
  • Case-sensitive (age and Age are different).
  • Cannot use Java reserved keywords (like int, class, public).
Best Practice: Use camelCase for variable names. Start with a lowercase letter and capitalize each subsequent word.
Examples: userName, accountBalance, isLoggedIn.

Variable Scope

The scope of a variable determines where it can be accessed within your code. Java has three main types of variables based on scope:

Java Variable Scope Diagram
  • Local Variables: Declared inside a method or block.
    Scope: Only inside that method/block. Recreated every time the method runs.
  • Instance Variables: Declared inside a class but outside methods.
    Scope: Accessible by all methods in the class. Specific to an object instance.
  • Static (Class) Variables: Declared with static keyword.
    Scope: Global to the class. Shared by all instances.
Output
Click Run to execute your code

Constants (final Keyword)

If you want a variable to be constant (meaning its value cannot be changed after initialization), use the final keyword.

final float PI = 3.14f;
// PI = 3.15f; // Compilation Error!
Convention: Constant variable names are usually written in UPPER_SNAKE_CASE.
Example: MAX_USER_LIMIT, DEFAULT_TIMEOUT.

Summary

  • Variables are containers for data with a specific Type and Name.
  • Use camelCase for naming variables.
  • Local variables exist only inside their block.
  • Instance variables belong to an object.
  • Static variables belong to the class.
  • Use final to create constants that cannot change.

What's Next?

Sometimes you need to convert data from one type to anotherโ€”like turning an integer into a double. In the next lesson, we'll learn about Type Casting and how to handle data conversion safely.