Variables in Java
Hey, everyone! In this guide, we'll explore the concept of variables in Java. Variables are essential in programming, allowing you to store and manipulate data dynamically. Let's dive in!
1. What is a Variable?
A variable is a container that holds data that can be used and modified throughout a program. Each variable in Java has:
- Data type: Defines the type of value it can hold (e.g.,
int,double,char). - Name: A unique identifier used to refer to it.
- Value: The data or information stored in the variable.
Video Explanation

Syntax
dataType variableName = value;
Example
int age = 25;
double salary = 55000.50;
In this example:
- age is an int variable holding the value 25.
- salary is a double variable holding the value 55000.50.
2. Types of Variables in Java
Java provides different types of variables categorized by scope and purpose:
- Instance Variables
- Class (Static) Variables
- Local Variables
2.1. Instance Variables
- Declared inside a class but outside any method or constructor.
- Each object of the class has its own copy of the instance variables.
- Initialized to default values if not explicitly initialized.
Example
public class Person {
String name; // Instance variable
int age; // Instance variable
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
In this example:
- name and age are instance variables for each Person object.
2.2. Class (Static) Variables
- Declared with the
statickeyword inside a class. - Shared across all instances of a class, meaning all objects share the same copy.
- Used for memory management or when a variable’s value is supposed to be the same across all instances.