JavaBasics

Java Variables

Learn what variables are in Java, how to declare and initialize them, variable types, scope, and naming conventions with examples.

Java VariablesLink to this section

Variables are used to store data values in a Java program. They act as containers that hold information which can be changed during program execution.

Understanding variables is fundamental because almost every Java program works with data stored in variables.

What is a Variable?Link to this section

A variable is a named memory location that stores a specific type of data. Each variable in Java must have a data type and a unique name.

note

Java is a strongly typed language, so the data type of a variable must be declared.

Declaring Variables in JavaLink to this section

Variable declaration tells the compiler what type of data a variable will store.

Variables can be declared first and initialized later.

warning

Using an uninitialized local variable will cause a compilation error.

Initializing VariablesLink to this section

Initialization means assigning a value to a variable.

Types of Variables in JavaLink to this section

Java variables are classified based on their scope and lifetime.

  • Local Variables – Declared inside methods
  • Instance Variables – Belong to an object
  • Static Variables – Shared among all objects of a class

Local VariablesLink to this section

Local variables are declared inside methods or blocks and are accessible only within that block.

note

Local variables do not have default values.

Instance VariablesLink to this section

Instance variables are declared inside a class but outside methods. Each object of the class gets its own copy.

Static VariablesLink to this section

Static variables are declared using the static keyword. They are shared among all instances of a class.

tip

Use static variables for data that should be common to all objects.

Java Variable Naming RulesLink to this section

Java follows strict naming rules for variables:

  • Must begin with a letter, underscore (_), or dollar sign ($)
  • Cannot start with a number
  • Cannot use Java reserved keywords
  • Case-sensitive

warning

Poor variable names reduce code readability and increase maintenance cost.
Java Variables
Question 1 of 5

What is the main purpose of a variable in Java?

Java Variables

medium
  1. Declare one variable of each primitive data type and print their values.
  2. Write a program that uses a static variable to count the number of objects created for a class.
  3. Create a class with two instance variables and display their values using an object.
  4. Declare a local variable inside a method and try accessing it outside the method. Observe the error.
  5. Rename poorly named variables in a sample program to meaningful names and explain the improvement.