Types of Variables in Java with Examples

Types of Variables in Java with Examples


In Java, variables are classified into different types based on their scope, lifetime, and how they are stored. The main types of variables in Java are:

1. Local Variables

  • Declared inside a method, constructor, or block.
  • Can only be used within that method or block.
  • Must be initialized before use.
  • Stored in the stack memory.

Example:

java

public void display() {

    int x = 10; // Local variable

    System.out.println(x);

}

2. Instance Variables (Non-Static Variables)

  • Declared inside a class but outside any method.
  • Each object of the class gets its own copy.
  • Stored in the heap memory.
  • Default values are assigned (e.g., 0 for integers, null for objects).

Example:

java

class Person {

    String name; // Instance variable

}

3. Static Variables (Class Variables)

  • Declared using the static keyword inside a class but outside methods.
  • Shared among all instances of the class.
  • Stored in the method area (static memory).
  • Default values are assigned automatically.

Example:

java

class Employee {

    static String company = "TechCorp"; // Static variable

}

4. Final Variables (Constants)

  • Declared using the final keyword.
  • Once assigned, their value cannot be changed.
  • Can be local, instance, or static.

Example:

java

final int MAX_VALUE = 100; // Final variable

5. Volatile Variables

  • Declared using the volatile keyword.
  • Used in multithreading to ensure visibility of changes to variables across threads.

Example:

java

class SharedData {

    volatile int counter = 0; // Volatile variable

}

6. Transient Variables

  • Used in serialization to exclude a variable from being serialized.
  • Declared using the transient keyword.

Example:

java

class User implements Serializable {

    transient String password; // Transient variable

}

Let me know if you need more details! 🚀

 





Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
https://otieu.com/4/9433883
https://otieu.com/4/9433883