Introduction
A variable specifies a memory location that contains data. The data can be numbers, characters and so on. There are three types of variables in Java:
- Local variables
- Instance variables
- Class variables
Local variables
- A method uses local variables for storing its temporary state.
- Generally, these are declared inside the methods, constructors or blocks of code.
- These should always be declared and initialized before their use.
- We cannot access local variables anywhere other than the specific methods, constructors or blocks of code in which they are declared.
- When the method is executed completely, these local variables are destroyed.
Example:
- package myclass1;
- class Myclass1 {
- public void classStrength() {
- int strength = 100;
- strength = strength - 10;
- System.out.println("Class strength is : " + strength);
- }
- public static void main(String args[]) {
- Myclass1 count = new Myclass1();
- count.classStrength();
- }
- }
Output:
Instance variables
- These are also known as non-static variables.
- These are declared inside a class, but outside a method, constructor or a block of code.
- Instance variables have a default value.
- These are created and destroyed when the object is created and destroyed respectively.
- Inside the class these can be accessed directly by calling their names.
- Instance variables can be accessed by all methods, constructors or blocks of code in the same class.
Example:


Join the conversation! Your thoughts help the community grow.