Java-Variable
A variable is a container that holds data. It allows you to store and modify values in memory.
Key Points:
- A variable is a named memory location for storing data.
- Declaration: Specify the data type and variable name.
- Initialization: Assign a value to the variable.
Declaration & Initialization
Declaration & Initialization
To declare a variable first write datatype ( type of data i.e. int, float, char, etc.) then space , and then write the name of the variable (Identifier).
Syntax:
datatype variable_name;
Example:
int a; // Declaring a variable
To initialize a variable we have to assign a value to the variable.
Syntax:
variable_name = value;
Example:
a = 12; // Assigning value
Declaration and Initialization of a variable at once:
int a=20;
String s="Hello";
Types of Variables in Java
Types of Variables in Java
Variables are of three types: Instance, Local, Static.
1. Instance Variable
- Defined inside a class but outside methods.
- Each object gets its own copy of the instance variable.
Example:
package quipohouse;
public class InstanceVariable {
int var = 10; // Declaration and initialization of instance variable
public static void main(String[] args) {
InstanceVariable c = new InstanceVariable();
System.out.println(c.var);
}
}
Output:
10
2. Local Variable
- Declared inside a method or block.
- Scope limited to that method/block.
Example:
package quipohouse;
public class LocalVariable {
public static void main(String[] args) {
int var2 = 12; // Declaration and initialization of Local Variable
System.out.println(var2);
}
}
Output:
12
3. Static Variable
- Declared using
static
inside a class. - Shared across all objects of the class (single copy).
- Can be accessed directly using the class name.
Example:
package quipohouse;
public class StaticVariable {
static int var; // Declaration of static variable
public static void main(String[] args) {
System.out.println(StaticVariable.var); // 0
System.out.println(var); // 0
}
}
Output:
0
0