Static vs Non-Static Methods in Java & For Loop vs While Loop
By Bhau Automation • Java Programming Tutorial
🎯 What You Will Learn
- Static Method in Java
- Non-Static Method in Java
- Differences between static and non-static methods
- For loop vs while loop
- Java examples with output
- Interview questions
💡 Pro Tip: Mastering static methods and loops greatly improves your Java coding efficiency.
📌 What is a Static Method?
A static method belongs to the class and can be accessed without creating an object.
class Test {
static void show() {
System.out.println("Static Method");
}
public static void main(String[] args) {
show();
}
}
📌 What is a Non-Static Method?
A non-static method requires an object for execution.
class Demo {
void display() {
System.out.println("Non-static Method");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.display();
}
}
📊 Difference: Static vs Non-Static Method
| Feature | Static Method | Non-Static Method |
|---|---|---|
| Class/Object | Class based | Object based |
| Access | Direct | Using Object |
| Memory | One copy | Multiple copies |
| Used for | Common logic | Object logic |
🔁 For Loop in Java
Used when the number of iterations is known.
for(int i=1;i<=5;i++){
System.out.println(i);
}
🔁 While Loop in Java
Used when the number of iterations is unknown.
int i=1;
while(i<=5){
System.out.println(i);
i++;
}
🔍 Difference: For Loop vs While Loop
| Feature | For Loop | While Loop |
|---|---|---|
| Use | Known iterations | Unknown iterations |
| Initialization | Inside loop | Outside |
| Readability | Compact | Readable |
❓ Interview Questions
Q1: Can we overload static methods? ✅ Yes
Q2: Can static method access non-static data? ❌ No
Q3: Difference between for and while loop? ✅ Control & usage
Q4: Can main() be overloaded? ✅ Yes
Q2: Can static method access non-static data? ❌ No
Q3: Difference between for and while loop? ✅ Control & usage
Q4: Can main() be overloaded? ✅ Yes
🎥 Watch Full Java Video Tutorial
📺 Click Here to Watch Java Tutorial on YouTube
✅ Key Takeaways
- Static methods do not need objects
- Non-static methods need objects
- For loop = count controlled
- While loop = condition controlled
- Both are essential in Java development
🚀 Created by Bhau Automation