DEV Community

LAKSHMI G
LAKSHMI G

Posted on

Java Variable

A variable in Java is a named memory location used to store data that can change during program execution.

Variable = name + memory + value

Why use variables

  • Store data temporarily in memory
  • Reuse values multiple times
  • Perform calculations
  • Make programs dynamic and flexible
  • Improve code readability and maintenance

How is a variable created in Java

variable is created in two steps:

1.Declaration (Memory allocation)

- int age;
- Tells Java what type of data to store
- Reserves memory

2.Initialization (Assign value)

  Stores the value in allocated memory
  int age = 25
Enter fullscreen mode Exit fullscreen mode

When is a variable created?
It depends on the type of variable
Java has 4 main types of variables based on where and when
memory is allocated.

1. Local Variable

** Where created?**
Inside a method, constructor, or block

When created?
When the method is called

When destroyed?
When the method execution ends

Memory location: Stack

void show() {
    int x = 10; // local variable
}
Enter fullscreen mode Exit fullscreen mode
  • Must be initialized before use
  • No default value

2.Instance Variable (Non-static)

Where created?
Inside class but outside methods

When created?
When an object is created using new

** When destroyed?**
When object is destroyed (GC)

Memory location: Heap

class Student {
    int id; // instance variable
}

Student s = new Student(); // instance variable created here


Enter fullscreen mode Exit fullscreen mode

Gets default value
One copy per object

3.Static Variable (Class Variable)

Where created?
Inside class with static keyword

** When created?**
When class is loaded into JVM

When destroyed?
When class is unloaded

Memory location: Method Area (Class Area)


class College {
    static String collegeName = "ABC College";
}
Enter fullscreen mode Exit fullscreen mode

Single copy shared by all objects
Access using class name

4.Parameter Variable

Where created?
In method parameter list

When created?
When method is called

Memory location: Stack

void add(int a, int b) {
    int sum = a + b;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)