What happens if we remove static modifier from the main method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

What happens if we remove static modifier from the main method?

4th Feb 2022, 2:49 AM
😇🌟SWATI🌟😇
😇🌟SWATI🌟😇 - avatar
3 Answers
+ 7
L.M.Paredes thank you 😊
4th Feb 2022, 3:09 AM
😇🌟SWATI🌟😇
😇🌟SWATI🌟😇 - avatar
+ 8
Error: Main method is not static in class Main, please define the main method as: public static void main(String[] args) Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.
4th Feb 2022, 3:08 AM
L.M.Paredes
L.M.Paredes - avatar
+ 2
The modifier 'static' is used for memory management in java. We can call any method defined as static in our program even without first creating its object. So, the object is not created and hence we save the memory. I will try to explain this by an example. Let us suppose that we defined a normal or non static method in our program that return sum of two numbers A & B. Now we call this in our main method by creating one instance. In the same way, if we create ten instances (object) of its class then every time the object is created, it will require that much memory. Now, because i required this method multiple times in my program it had create it object first which in turn used more memory. But if we had defined this method as static, we could use it as many times as we require in our program without creating its object or instance. Hence saving the memory. So my friend, this is why main method is defined as static in order to save memory.
5th Feb 2022, 4:02 PM
Gulshan