Loading...

Variable Types in Java

In Java, there are three distinct types of variables. Understanding where they are declared and their scope is crucial for memory management.

Local Variables Instance Variables Static Variables

1. Local Variables

  • Scope: Declared in methods, constructors, or blocks. Visible only within that block.
  • Creation/Destruction: Created when the block is entered, destroyed when exited.
  • Storage: Implemented at the stack level internally.
  • No Defaults: There is no default value. You must initialize them before use.
  • Restrictions: Access modifiers (public, private, etc.) cannot be used.

2. Instance Variables

  • Declaration: Declared inside a class but outside methods/blocks.
  • Storage: Allocated in the Heap when an object is created (using `new`).
  • Lifecycle: Created with the object and destroyed when the object is garbage collected.
  • Access: Visible to all methods in the class. Usually declared `private` to ensure encapsulation.
  • Default Values: Numbers = `0`, Boolean = `false`, Objects = `null`.
  • Accessing: Can be accessed directly inside the class or via Fully Qualified Name in static contexts.

3. Static (Class) Variables

  • Keyword: Declared using the `static` keyword.
  • Memory: Only one copy exists per class, shared by all objects. Stored in static memory.
  • Lifecycle: Created when the program starts, destroyed when it stops.
  • Constants: Often used with `final` to create constants (e.g., `public static final double PI`).
  • Access: Can be accessed using the class name (e.g., `ClassName.variableName`).
  • Defaults: Same default values as instance variables (0, false, null).

Complete List of Java Keywords

Note: assert was added in 1.4, enum in 1.5.

abstractbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodoubleelseextendsfinalfinallyfloatforgotoifimplementsimportinstanceofintinterfacelongnativenewpackageprivateprotectedpublicreturnshortstaticstrictfpsuperswitchsynchronizedthisthrowthrowstransienttryvoidvolatilewhileassertenum