Variables & Data Types

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Variables are named memory locations used to store data.
  • Java is strongly typed: Every variable must be declared with a specific data type before it can be used.
  • There are three types of variables in Java: Local variables, Instance variables (fields), and Static variables (class variables).

Concept

Variable Declaration & Initialization

In Java, you must declare the type of a variable. You can optionally initialize it with a value at the same time.

// Declaration
int myNumber;

// Initialization
myNumber = 42; 

// Declaration & Initialization
String myName = "Alice";

Types of Variables

  1. Local Variables: Declared inside a method, constructor, or block. They are destroyed when the block is exited. They must be initialized before use, as they do not get default values.
  2. Instance Variables (Fields): Declared inside a class but outside any method. They belong to a specific instance (object) of the class. They get default values (e.g., 0 for int, null for objects).
  3. Static Variables (Class Variables): Declared with the static keyword inside a class. There is only one copy of this variable shared among all instances of the class.

Examples

public class VariableExample {
    // 1. Static Variable (shared across all objects)
    static int globalCount = 0; 
    
    // 2. Instance Variable (unique to each object)
    String instanceName; 
    
    public VariableExample(String name) {
        this.instanceName = name;
        globalCount++; // Accessing static variable
    }
    
    public void printInfo() {
        // 3. Local Variable (only lives inside this method)
        int localAge = 30; 
        
        System.out.println("Name: " + instanceName + ", Age: " + localAge);
    }
}

Interview Questions

Q: Can a local variable have an access modifier (like public or private)?
A: No. Local variables belong exclusively to the block they are defined in. They cannot be accessed from outside that block anyway, so access modifiers are not allowed and will cause a compilation error.

Q: What is the difference between an instance variable and a static variable?
A: An instance variable has a separate copy for every object created from the class. If you change it in Object A, it doesn’t affect Object B. A static variable has only one copy that is shared among all objects of the class. If you change it in Object A, Object B sees the changed value.

Q: Can you use a local variable without initializing it?
A: No. Unlike instance variables which get default values (like 0 or null), the Java compiler forces you to explicitly initialize local variables before you use them. Attempting to read an uninitialized local variable results in a compile-time error.