Sitemap

Member-only story

Static vs. Non-Static Methods in Java (Java Interview QA)

Learn the core differences between static and non-static methods in Java with real examples. Understand when and how to use them in your applications.

2 min readApr 2, 2025

Introduction

In Java, you can define two types of methods:

  • 🔹 Static methods — belong to the class.
  • 🔸 Non-static methods — belong to an object (instance).

Let’s explore the differences with examples and when to use each.

Key Differences: Static vs Non-Static

1. Static Method Example

public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}

Usage:

int sum = MathUtils.add(10, 5); // No need to create an object

💡 Static methods are great for utility functions like Math.pow(), Arrays.sort().

2. Non-Static Method Example

public class Person {
private String name;

public Person(String name) {
this.name = name;
}

public void greet() {
System.out.println("Hi, my name is " + name);
}
}

Usage:

Person p = new Person("Ramesh");
p.greet(); // Requires an object

💡 Non-static methods can access instance variables like name.

🚫 Can Static Methods Access Non-Static Members?

No! Because static methods don’t know which object to refer to.

public class Test {
int number = 10;

public static void show() {
// System.out.println(number); ❌ Compile-time error
}
}

To fix it, either:

  • Make number static,
  • Or use a reference of the object inside the static method.

🎯 When to Use What?

Summary

  • Static method = Class-level method, doesn’t require an object.
  • Non-static method = Object-level method, can access instance variables.
  • ⚠️ Use static only when the method doesn’t need object state.

🔚 Final Thoughts

Understanding when to use static vs. non-static methods helps you:

  • Write cleaner, modular code
  • Avoid unnecessary object creation
  • Make your application more memory-efficient

Think: “Is this logic tied to a specific object? If not — maybe it should be static.”

--

--

No responses yet