DEV Community

Mohan Mogi
Mohan Mogi

Posted on

Java Static Variable vs Non-Static Variable (Beginner Guide)

A variable in Java stores data. Variables can be of two types:
1.Static Variable (Class Variable)
2.Non-Static Variable (Instance Variable)

1.Static Variable:

  1. Belongs to *A static variable belongs to the class, not to any individual object.

2.Keyword
*A static variable is declared using the static keyword.

  1. Number of Copies
    *Only one copy of the static variable exists, and it is shared by all objects.

  2. Memory Creation
    *Memory for a static variable is created once when the class is loaded into memory.

  3. Access
    *A static variable is usually accessed using the class name, for example: Student.college.

  4. Shared
    *A static variable is shared by all objects of the class.

  5. Use
    *A static variable is used to store common data that is the same for every object, such as a company name or college name.

2.Non-Static Variable:

  1. Belongs to *A non-static variable belongs to an object (instance) of the class.

2.Keyword
*A non-static variable is declared without the static keyword.

  1. Number of Copies
    *Every object has its own separate copy of the non-static variable.

  2. Memory Creation
    *Memory for a non-static variable is created each time a new object is created.

  3. Access
    *A non-static variable is accessed using an object, for example: student.name.

  4. Shared
    *A non-static variable is not shared. Each object has its own value.

  5. Use
    *A non-static variable is used to store individual object data, such as a student's name, roll number, or age.

Top comments (0)