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:
- 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.
Number of Copies
*Only one copy of the static variable exists, and it is shared by all objects.Memory Creation
*Memory for a static variable is created once when the class is loaded into memory.Access
*A static variable is usually accessed using the class name, for example: Student.college.Shared
*A static variable is shared by all objects of the class.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:
- 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.
Number of Copies
*Every object has its own separate copy of the non-static variable.Memory Creation
*Memory for a non-static variable is created each time a new object is created.Access
*A non-static variable is accessed using an object, for example: student.name.Shared
*A non-static variable is not shared. Each object has its own value.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)