Skip to content
beginnerPhase 11 · Java OOP

this and static

Understand the this keyword and static variables/methods.

45m
2 problems
Topic Progress0%

This Keyword

The this Keyword

this is a reference to the current object.

Disambiguating Variables

public class Person {
    private String name;
    
    public Person(String name) {
        this.name = name;  // this.name = instance var
    }
    
    public void setName(String name) {
        this.name = name;
    }
}

Returning Current Object

public class Builder {
    private String value;
    
    public Builder setValue(String value) {
        this.value = value;
        return this;  // Enable method chaining
    }
}

Builder b = new Builder().setValue("hello").setValue("world");

Passing this as Parameter

public class EventSource {
    public void register(EventListener listener) {
        listener.subscribe(this);
    }
}

this() for Constructor Chaining

public class Rectangle {
    int width, height;
    
    public Rectangle() {
        this(10, 10);  // Call 2-arg constructor
    }
    
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

Static Variables

Static Variables

Static variables are shared among all instances of a class.

Declaration

public class Counter {
    int count;           // Instance variable
    static int total;    // Static variable
    
    public void increment() {
        count++;
        total++;
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();

c1.increment();
c1.increment();
c2.increment();

System.out.println(c1.count);  // 2
System.out.println(c2.count);  // 1
System.out.println(Counter.total);  // 3 (shared)

Accessing Static Members

public class MathUtils {
    public static final double PI = 3.14159;
    
    public static int square(int n) {
        return n * n;
    }
}

// Access via class name
int result = MathUtils.square(5);
double pi = MathUtils.PI;

// Can also access via instance (not recommended)
MathUtils obj = new MathUtils();
int r = obj.square(5);  // Works but not ideal

When to Use Static

public class StringUtils {
    // Utility methods - no instance state
    public static boolean isEmpty(String s) {
        return s == null || s.isEmpty();
    }
    
    public static String capitalize(String s) {
        if (s.isEmpty()) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
}

// Call without instantiation
boolean empty = StringUtils.isEmpty("");

Constants

public class Config {
    public static final String APP_NAME = "MyApp";
    public static final int MAX_RETRIES = 3;
    public static final double VERSION = 1.0;
}

// Access directly
String name = Config.APP_NAME;

Static vs Instance

Feature Static Instance
Memory One copy One per object
Access ClassName.member object.member
this keyword Cannot use Can use
Lifecycle Class load to unload Object creation to GC

Static Methods

Static Methods

Static methods belong to the class, not any instance.

Basic Usage

public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static int multiply(int a, int b) {
        return a * b;
    }
}

// Call without object
int sum = Calculator.add(5, 3);
int product = Calculator.multiply(5, 3);

Limitations

public class MyClass {
    int instanceVar = 10;
    static int staticVar = 20;
    
    public static void staticMethod() {
        // System.out.println(instanceVar);  // COMPILE ERROR!
        System.out.println(staticVar);  // OK
        // Cannot use 'this' keyword
        // Cannot call instance methods directly
    }
    
    public void instanceMethod() {
        System.out.println(instanceVar);  // OK
        System.out.println(staticVar);    // OK
        staticMethod();                    // OK
    }
}

Factory Methods

public class Color {
    private int r, g, b;
    
    private Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
    
    public static Color red() {
        return new Color(255, 0, 0);
    }
    
    public static Color green() {
        return new Color(0, 255, 0);
    }
    
    public static Color blue() {
        return new Color(0, 0, 255);
    }
}

Color red = Color.red();

Utility Methods

public class StringUtils {
    public static boolean isEmpty(String s) {
        return s == null || s.isEmpty();
    }
    
    public static String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }
    
    public static boolean isPalindrome(String s) {
        return s.equals(reverse(s));
    }
}

// Call without instantiation
boolean empty = StringUtils.isEmpty("");
String reversed = StringUtils.reverse("hello");

Static Blocks

Static Initialization Blocks

Static blocks run once when the class is first loaded.

Basic Static Block

public class Config {
    static Map<String, String> settings;
    
    static {
        settings = new HashMap<>();
        settings.put("host", "localhost");
        settings.put("port", "8080");
        settings.put("debug", "true");
    }
}

Multiple Static Blocks

public class Example {
    static int a;
    static int b;
    
    static {
        a = 10;
        System.out.println("Static block 1: a = " + a);
    }
    
    static {
        b = a * 2;
        System.out.println("Static block 2: b = " + b);
    }
}
// Output when class loaded:
// Static block 1: a = 10
// Static block 2: b = 20

Static Block vs Static Method

public class Example {
    static int value;
    
    // Static block - runs automatically
    static {
        value = computeValue();
    }
    
    // Static method - must be called
    static int computeValue() {
        return 42;
    }
}

Lazy Initialization

public class Singleton {
    private static Singleton instance;
    
    private Singleton() { }
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Static Inner Classes

public class Outer {
    private int outerVar = 10;
    
    public static class Inner {
        // Cannot access outer instance variables
        // Can access outer static members
        public void print() {
            System.out.println("Static inner class");
        }
    }
}

Outer.Inner inner = new Outer.Inner();
inner.print();

When to Use

// 1. Utility classes (all static methods)
public class MathUtils { }

// 2. Constants
public class Constants { }

// 3. Factory methods
public class Factory { }

// 4. Initialization of static state
public class Config { }

Practice Problems

0/2solved
Design HashSet
Class Design

Design a HashSet without using built-in hash table libraries.

Example:

Input: HashSet set = new HashSet(); set.add(1); set.contains(1)

Output: true

Basic HashSet operations

Optimal Solution — O(1) time, O(n) space

Use boolean array for O(1) operations.

class MyHashSet {
    private boolean[] data;
    public MyHashSet() { data = new boolean[1000001]; }
    public void add(int key) { data[key] = true; }
    public void remove(int key) { data[key] = false; }
    public boolean contains(int key) { return data[key]; }
}

Edge Cases:

  • Add duplicate
  • Remove non-existent
  • Contains after remove
Design HashSet with Bucket
Class Design

Design HashSet using bucket array with collision handling.

Example:

Input: set.add(1); set.add(2); set.contains(1)

Output: true

Bucket-based storage

Optimal Solution — O(1) average time, O(n) space

Use array of LinkedLists for bucket storage.

class MyHashSet {
    private static final int BUCKET_SIZE = 769;
    private LinkedList<Integer>[] buckets;
    public MyHashSet() {
        buckets = new LinkedList[BUCKET_SIZE];
        for (int i = 0; i < BUCKET_SIZE; i++)
            buckets[i] = new LinkedList<>();
    }
    private int getBucket(int key) { return key % BUCKET_SIZE; }
}

Edge Cases:

  • Many collisions
  • All same bucket
  • Empty set

Quiz

1. What does the 'this' keyword refer to?

Question 1 options

2. What is a static variable?

Question 2 options

3. Can a static method use 'this'?

Question 3 options

4. What is the primary purpose of this and static?

Question 4 options

Flashcards

Question

What is the difference between static and instance variables?

Answer

Static variables are shared across all instances. Instance variables are unique to each object.

Question

When does a static block execute?

Answer

When the class is first loaded by the JVM, before any objects are created.

Question

Can static methods access instance variables?

Answer

No. Static methods don't have a 'this' reference, so they cannot access instance members.

Question

What is this and static?

Answer

this and static is a key concept in Java programming.

Question

When to use this and static?

Answer

Use this and static when building production systems that require reliability, scalability, and maintainability.

Revision Notes

Key Takeaways

  • 1.this refers to current object
  • 2.static members are shared
  • 3.static methods cannot use this
  • 4.static blocks initialize static state

Interview Tips

  • Know when to use static vs instance
  • Understand static initialization order
  • Use static for utility methods
  • Know static inner class limitations

Cheat Sheet

Cheat Sheet

  • this: current object reference
  • this(): chain constructors (must be first)
  • static: shared across all instances
  • static method: belongs to class
  • static block: runs on class load