TYPES OF VARIABLE
VARIABLE:
In Java, variables serve as storage containers for data types like numbers, text, and objects.
TYPES OF VARIABLES IN JAVA: (3 types)
- Local variable
- Instance variable
- Static variable
Local variable
- A local variable is one that is declared inside the method body. Only that method may utilize this variable, and none of the other methods in the class are even aware that it exists.
- A local variable cannot be defined with “static” keyword.
Instance variable:
- An instance variable is created when an Object class is generated and it gets destroyed when the same object class is destroyed
- Programmers can use access specifiers for instance variables
- It is not mandatory to initialize instance variables
Static Variable:
- A variable that is declared as static is called a static variable.
- It cannot be local.
- You can create a single copy of the static variable and share it among all the instances of the class.
STATIC VS NON-STATIC:
FEATURE | STATIC VARIABLE | NON-STATIC VARIABLE |
Definition | A static variable is a variable that is declared using the static keyword. | A non-static variable is a variable that is not declared using the static keyword. |
Access | Can be accessed using class name. | Can be accessed using object reference. |
Scope | Scope is limited to the class. | Scope is limited to the object. |
Initialization | Initialized only once when the class is loaded | Initialized each time an object is created. |
Usage | Used to represent class-level data. | Used to represent object-level data. |
Example | static int count = 0; | public int age; private String name; |
Inheritance | Can be inherited by the subclass. | Cannot be inherited by the subclass. |
Life Cycle | It is created when the class is loaded and destroyed when the class is unloaded. | It is created when the object is created and destroyed when the object is garbage collected. |
Static variables:
- Static variables in Java are class-level variables that are shared among all objects of a class.
- They are declared using the “static” keyword and are stored in the class area.
- They are also known as class variables.
SYNTAX: accessSpecifier static dataType variableName;
Example: public static int age=12;
Non-static variables:
Non-static (also known as an instance) variables in Java are specific to a single instance of a class and can hold different values for each object of the class.
SYNTAX: accessSpecifier dataType variableName;
Example: private int age;
public String name;
float mark; //default

Output

Advertisements
Comments
Post a Comment