Java Static vs Non-Static Methods & Difference Between For Loop and While Loop
By Bhau Automation β’ Java Programming for Beginners to Advanced
π What Are Static Methods in Java?
A static method belongs to the class, not the object. You can call it without creating an instance of the class.
β Key Features of Static Methods
- Accessible without object creation
- Used for utility or helper methods
- Can access only static variables
- Memory allocated once at class loading
class Demo {
static void show() {
System.out.println("This is a static method");
}
public static void main(String[] args) {
Demo.show(); // calling without object
}
}
π What Are Non-Static Methods in Java?
A non-static method belongs to the object. You must create an object before calling it.
β Key Features of Non-Static Methods
- Require object creation to call
- Can access both static & non-static data
- Each object has its own copy
- Used for object-specific behavior
class Demo {
void display() {
System.out.println("This is a non-static method");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.display();
}
}
π Static vs Non-Static Method β Quick Comparison
| Static Method | Non-Static Method |
|---|---|
| Called without an object | Requires object creation |
| Can access only static variables | Can access both static & non-static |
| Loads in memory once | Separate for every object |
π For Loop vs While Loop in Java
Both loops repeat code, but differ in structure and usage.
β For Loop
Used when the number of iterations is known.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
β While Loop
Used when iterations depend on a condition, not count.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
π For Loop vs While Loop β Comparison
| For Loop | While Loop |
|---|---|
| Used when iteration count is known | Used when count is unknown |
| Initialization in loop header | Initialization outside |
| Compact and clean | More flexible |
π― Interview Questions from This Topic
- Why canβt static methods use non-static variables?
- Can a non-static method call a static method?
- Which loop is better β for or while?
- What happens if while loop condition never becomes false?
π₯ Watch Full Tutorial
π Watch on YouTube
π Created with β€οΈ by Bhau Automation