Java - Variable Types

There are three types :
  1. Local variables
  2. Instance variables
  3. Class/static variables
  1. Local variables
    • Local variables are declared in methods, constructors, or blocks.
    • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
    • Local variables are visible only within the declared method, constructor or block.
    • Access modifiers cannot be used for local variables.
    • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
  2. Instance variables
    • Instance variables are declared in a class, but outside a method, constructor or any block.
    • Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
    • Access modifiers can be given for instance variables.
    • Instance variables have default values.
  3. Class/ static variables
    • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
    • Static variables are created when the program starts and destroyed when the program stops.
    • Static variables can be accessed by calling with the class name ClassName.VariableName.
    • Access modifiers can be given for instance variables.
    • Default values are same as instance variables.

BytecodeTechnosolutions.com | Raju