Why main method is static in java?
Hello friends,
I recently started learning java language. I know that static methods use only static variables in java, but Main method in java is also static and it can use any variable along with static variable. I don't know why this is. I don't know why main method is static in java? Please help me.
Thank you.
Re: Why main method is static in java?
Yes, Main method of class is static in java. This is used to create an instance of your class explicitly. If we didn't use static before Main method, then we will not bale to create new object of class. Main method is also declare static to call this method first before creating any object.
Code:
class ProgramEg
{
public static void main(String[] args)
{
new Program().runs();
}
public void runs()
{
// Create instance of the object
}
}
Re: Why main method is static in java?
To avoid ambiguity of which constructor to called, Main method is declare static. Especially if your class looks like this:
Code:
public class JavaClassEg{
protected JavaClassEg(int k)
public void main(String[] args){
}
}
In above code what Should the JVM call JavaClassEg(int k)? What should it pass for K? If your answer is not then what should the JVM instantiate JavaClass?
Re: Why main method is static in java?
Main method is declared static because it is called on a class instance and not to an object of a class. It means that static method can't access instance variables. This is because they are only instantiated in an object. If you want to access static variable then you have to declare that variable static.
Code:
public class TestEg {
private static int values = 0;
public static void main(String[] args) {
values++;
}
}
Re: Why main method is static in java?
You have take wrong meaning of static statement. Statement is like "static methods can only use those instance variables that are defined static". It means that you can access ant variable, but you have to declared them static.
Code:
Class AE{
int a;
static int b;
public static void methodA(){
a = 9;
b = 3;
int k = 5;
}
}
Re: Why main method is static in java?
It's not true that "main method is static", you can declared Main method non-static also. You can do this in following ways. In the following code I have use TestEg class to include all methods. In the following code I have use "values" variable.
Code:
public class TestEg {
private static int values = 0;
public static void main(String[] argss) {
values++;
}
}