DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Local Variables, Instance Variables and Static Variables

What is Local Variables?

  • They are Created inside method/method parameters/arguments or blocks.
  • They can be accessed inside the method or block only.
  • There is no default value for the local variable. We must initialize them before using it. Otherwise will throw compile time error.
  • They are stored in stack memory.
  • They are created when method starts and destroyed when method ends.
  • From java 10 version, we can just decalre a local variable like var a = 10; without specifying the actual data type. The data type will be detected automatically by the compiler.

What is Instance variable ?

https://dev.to/nanthini_ammu_ac02ad32802/instanceobject-variable-44od

What is static variable ?

  • A static variable is a class-level variable shared by all objects, with only one copy in memory. If one object changes its value, it affects all others. -It is declared inside a class and outside a method.
  • We must use the static keyword while declaring it. Example: static int count;
  • It can be accessed by all methods in the class.
  • The static variable exists as long as the program runs, and it is created when the class is loaded.
  • Static variables have default values, such as 0 for int, false for boolean, and null for objects.
  • You can access it using the class name like ClassName.variableName.

Top comments (0)