Java Variables

Java variables provide us the name to store value. Different data type can be store in variable. Variable memory assignment will totally depend on the assigned data type (e.g. int, long, float, char).

Types of Variables

There are three types of variables in Java:

  1. local variable
  2. static variable
  3. instance variable

Local variable

  1. Variable declare inside method, constructor or block call as Local variable.
  2. Local variable gets memory at the time of execution of method, constructor and block.
  3. Its not allowed to use access modifier with variables.
  4. Local variable doesn’t have default value. Default value needs to be assign before invoking it.

Static variable

Static variable can be declare using static keyword as mentioned below.

 static int a = 10;
  1. Static variable is also called as class level variable. Static variable will be per class and will not depend on the number of objects of that class.
  2. Java don’t allow to create static variable inside function, constructor and block.
  3. Static variable allocates to static memory as soon as the class loads in the memory.
  4. Declaring class or static variable with “public static final” will make it as a constant where value cannot be reassign. As a best practice, developer must use capital letters and underscore to declare constant variable.

5. Static variable access with both class name and object.

6. Static variable can be access directly in the static method or static block.

7. Static variable can directly be using with name inside static method and static block.

Instance variable:

  1. Instance variable allocates memory in heap as soon as the instance is created for the class using new keyword.
  2. Same variable has different state for different class object.
  3. All four access modifiers can be given for instance variables.
  4. Instance variable can directly be access inside non static function, constructor and block using variable name.
  5. Instance variable have default values.
  6. Instance variables declare inside of class and outside of method, constructor and block.

Below is the best example where count behavior varies depending on class object. For object1 count value is 100 and for object2 count value is 0, same variable with different behavior.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan