Why is the Java main method static?
Asked Answered
A

37

542

The method signature of a Java mainmethod is:

public static void main(String[] args) {
    ...
}

Is there a reason why this method must be static?

Abnormal answered 28/9, 2008 at 19:45 Comment(2)
in this case, we shouldn't say the method signature, because the term refers only to method names and its parametersMooncalf
Java is deliberately designed to look familiar to a C programmer. This is very close to the C convention.Sweeney
R
354

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

public class JavaClass{
  protected JavaClass(int x){}
  public void main(String[] args){
  }
}

Should the JVM call new JavaClass(int)? What should it pass for x?

If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.

There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static.

I have no idea why main is always marked public though.

Rocher answered 28/9, 2008 at 19:45 Comment(16)
Of course, you are correct. public class JavaClass{ private static JavaClass initme = new JavaClass(); public void main(String[] args){ } } initme is initialized before main() is called. However, the main body of my answer still holds.Rocher
Why not use an entry-point interface to solve these problems; any main object would have to implement the interface.Bobbery
Implementing an interface does not solve the instantiation problem.Rocher
Well, if by convention we use public static void main..., why couldn't the convention be that the application entry point class should have a public default constructor?Indra
I personally like that public static void main serves as a marker of an entry point – a public parameterless constructor doesn't scream out "This is probably an entry point!" in the same way.Rocher
@EdwinDalorzo - What would be gained by forcing the entry point class to be instantiated? Calling a static method places the least amount of burden on the class. It's free to instantiate itself if that makes more sense for your design.Meuser
“which constructor should be called?” How is that even conceivably a problem? The same “problem” exists for the decision which main to call. Weirdly enough (for you), the JVM manages this just fine.Oniskey
The main method is always public because it has to be accessed by the runtime engine, the JVM.Derwent
May be this ambiguity can be resolved by just calling the default constructor although no default constructor exists in this case but this could have been marked as an exception , but then there would have been memory allocation overhead . Also , public is used so that JVM can access it , certainly default access provider won't work.Elliottellipse
Hmm... absolutely right, that's why JVM don't have to create newInstance() and it just invike() main method.Millican
main is made public static so that when you run a class from command line then compiler internally calls YourClass.main(args).Guildroy
This answer made sense to me once I realized that because main is not static in this example, the only way to call it - is to instantiate a JavaClass object and call main on that object. This implies that we must call a constructor for JavaClass, but which one, since we haven't had a chance to specify any code yet.Nasturtium
There is nothing wrong with defining that the main entry point is a given constructor on a class (taking a String[] argument), but the Java designers just made another decision.Sweeney
The main method is called by the JVM. JVM is outside the scope of the project. So if the main function is not public the JVM won't be aable to call the function.Montoya
@Sudheesh: the JVM is the very thing that enforces access modifiers. It can do whatever it wants with private methods.Rocher
@gthm: The JVM can access all methods, whether private or public. How would it be able to execute them otherwise?Rocher
P
438

This is just convention. In fact, even the name main(), and the arguments passed in are purely convention.

Java 21 introduced alternative conventions as a preview feature; you can omit the String[] parameter, the public modifier, and even the static modifier. If you omit the static modifier, an instance of the class will be created before the invocation, which requires that the class has a non-private zero-parameter constructor. The default constructor created by the compiler if no constructor has been declared, is sufficient.

When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that's right - java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge the virtual machine world, and the world of C, C++, etc... The reverse is also true - it is not possible (at least to my knowledge) to actually get a JVM running without using JNI.

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK) and have it do something entirely different. In fact, that's exactly what we do with all of our Java-based apps.

Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going (For example, in one case we are doing COM interoperability, and we actually pass a COM handle into main() instead of a string array).

So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is that it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function was important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.mycompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.

Pit answered 28/9, 2008 at 19:45 Comment(18)
+1: Very fascinating (especially the part about writing a custom java.exe)Lyndy
Honestly, while Jacob and Noah's answers are logical and probably partly what went through the minds of Gosling et al when designing the language, I think "convenience" and "C convention" as mentioned in the last paragraph are 99.9% of why the default is to use a public static method named main. The details of the executable's use of JNI to bootstrap the JVM, process the args, and pass them to whatever method it wants should win this answer the bounty.Meuser
Interesting, I do disagree with the "This is just convention." Part of the answer. The OP's primary question was the reason for static in the declaration. I don't think static in the main() declaration is just for the sake of convention. The fact that it's `main()' and not something else is feasible however.Hypnotize
@David So it did. I actually would have preferred an answer from one of the people originally involved – but that was a very far shot. Most of the other answers are unfortunately an exercise in ad-hoc reasoning. This one gives quite interesting details, besides having the humility not to invent wrong technical details to reason away a (probably) non-technical cause.Oniskey
@Hypnotize - Static methods are as close to C functions as you can get. A non-static method would require instantiating the class which isn't necessary in C.Meuser
@DavidHarkness I'm aware of this. I'm saying that static being required in the declaration of main() falls in line with the requirements of the language and not "just convention"Hypnotize
@Hypnotize - They could have required a public no-arg constructor and made main non-static and still fit within the bounds of the language. Without hearing from the designers, we'll just have to agree to disagree. :)Meuser
@James My pleasure. If you ever get a chance to write a little JNI launcher, I highly recommend it - it's not hard to do (there's plenty of examples online), and it'll give you a feel for part of the Java world that we normally take for granted.Pit
Why would JNI be involved here? java.exe is a native application. The JVM is a native library with a native entrypoint. Native application calling native entrypoint in a native library needs no JNI. JNI services are provided by the JVM -- therefore it should be apparent that JNI can't be used to load the JVM, since that would create a chicken-and-egg problem.Genro
@BenVoigt JNI is used for both directions (native -> JVM and JVM -> native). You use JNI to load the JVM, instruct it to load a class, locate the main method, and invoke that method. This is very much JNI. Contrary to popular belief, java.exe is not the Java VM - it is a thin wrapper that just loads the JNI DLL and invokes methods on it.Pit
@Kevin: But neither java.exe nor the JVM library it loads are Java bytecode. There's no JNI involved in loading the JVM, because there's no Java until the JVM is loaded.Genro
@BenVoigt You call LoadLibrary() to get the jvm dll. Then you call getprocaddress("JNI_CreateJavaVM"), then you invoke the JNI_CreateJavaVM function (docs.oracle.com/javase/1.4.2/docs/guide/jni/spec/… ). Once the VM is loaded you use standard JNI calls to find the correct class, load the static main method and invoke it. There's not a lot of room for misinterpretation there. JNI is absolutely how you load the VM. You may be used to writing only client side JNI using the native keyword, javah -jni, etc... but that's only half of JNI.Pit
@Kevin: Umm LoadLibrary is a native function.Genro
@BenVoigt I don't think this is productive at this point. Feel free to believe what you wish about it.Pit
This is the answer I was looking for. I had suspected the reasoning for the main method being static had something to do with the JNI, but Google wasn't coming up with much with the search terms I was using.Berghoff
Useful and interesting answer but doesn't answer the OP's questionDelanadelancey
This is an interesting and informative answer, but I feel it's actually badly wrong. The true reason is very simple - main is static so that the JVM doesn't have to create an object before calling it. That has nothing to do with convention.Rosarosabel
@DawoodibnKareem well, invoking the main method without constructing an instance is a convention, as much as constructing an instance through a zero-arg constructor, followed by invoking a non-static main method would be another convention. Which is, of course, easy to say in hindsight, as the other convention has been implemented now.Monogamous
R
354

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

public class JavaClass{
  protected JavaClass(int x){}
  public void main(String[] args){
  }
}

Should the JVM call new JavaClass(int)? What should it pass for x?

If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.

There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static.

I have no idea why main is always marked public though.

Rocher answered 28/9, 2008 at 19:45 Comment(16)
Of course, you are correct. public class JavaClass{ private static JavaClass initme = new JavaClass(); public void main(String[] args){ } } initme is initialized before main() is called. However, the main body of my answer still holds.Rocher
Why not use an entry-point interface to solve these problems; any main object would have to implement the interface.Bobbery
Implementing an interface does not solve the instantiation problem.Rocher
Well, if by convention we use public static void main..., why couldn't the convention be that the application entry point class should have a public default constructor?Indra
I personally like that public static void main serves as a marker of an entry point – a public parameterless constructor doesn't scream out "This is probably an entry point!" in the same way.Rocher
@EdwinDalorzo - What would be gained by forcing the entry point class to be instantiated? Calling a static method places the least amount of burden on the class. It's free to instantiate itself if that makes more sense for your design.Meuser
“which constructor should be called?” How is that even conceivably a problem? The same “problem” exists for the decision which main to call. Weirdly enough (for you), the JVM manages this just fine.Oniskey
The main method is always public because it has to be accessed by the runtime engine, the JVM.Derwent
May be this ambiguity can be resolved by just calling the default constructor although no default constructor exists in this case but this could have been marked as an exception , but then there would have been memory allocation overhead . Also , public is used so that JVM can access it , certainly default access provider won't work.Elliottellipse
Hmm... absolutely right, that's why JVM don't have to create newInstance() and it just invike() main method.Millican
main is made public static so that when you run a class from command line then compiler internally calls YourClass.main(args).Guildroy
This answer made sense to me once I realized that because main is not static in this example, the only way to call it - is to instantiate a JavaClass object and call main on that object. This implies that we must call a constructor for JavaClass, but which one, since we haven't had a chance to specify any code yet.Nasturtium
There is nothing wrong with defining that the main entry point is a given constructor on a class (taking a String[] argument), but the Java designers just made another decision.Sweeney
The main method is called by the JVM. JVM is outside the scope of the project. So if the main function is not public the JVM won't be aable to call the function.Montoya
@Sudheesh: the JVM is the very thing that enforces access modifiers. It can do whatever it wants with private methods.Rocher
@gthm: The JVM can access all methods, whether private or public. How would it be able to execute them otherwise?Rocher
T
197

The main method in C++, C# and Java are static.

This is because they can then be invoked by the runtime engine without having to instantiate any objects then the code in the body of main will do the rest.

Tribune answered 28/9, 2008 at 19:45 Comment(7)
Alright but couldn't the runtime instantiate one object of the class? And then call the Main method? Why?Hibbitts
How would the JVM know which constructor to call, if your main class had overloaded constructors? What parameters would it pass?Rocher
@Noah when you say parent class do you mean the class containing the main method? Because if so, the term "parent class" is rather confusing here, and otherwise it would make no sense to me. Also, if by convention we use public static void main..., why couldn't the convention be that the application entry point class should have a public default constructor?Indra
@Jacob How would the JVM know which overloaded static void main to call? Not a problem at all.Oniskey
Since main has to be a static method, what if I have to call foo() and bar() from main? They would have to be static too right? Because static method cannot reference non-static method. Now, if foo and bar call some other functions in turn, then they would have to be static too! So, we'd end up with all functions being static. But, I feel I'm missing something here. Because this can't happen.Angie
@Namratha: Yes, you're missing something. It's just not true that "static method cannot reference non-static method". The correct statement is: "Every static method must provide an object when using any non-static method". And look, static methods such as main frequently use new to create such an object.Genro
In C++, static int main won't compile: cannot declare '::main' to be static. On the other hand, in C, it will compile and then fail on the linker when it tries to make sense of the OS's reference to main: In function _start: (.text+0x20): undefined reference to 'main'. Because you made it static, making it impossible for an external compilation unit to "see" it.Appealing
C
42

Let's simply pretend, that static would not be required as the application entry point.

An application class would then look like this:

class MyApplication {
    public MyApplication(){
        // Some init code here
    }
    public void main(String[] args){
        // real application code here
    }
}

The distinction between constructor code and main method is necessary because in OO speak a constructor shall only make sure, that an instance is initialized properly. After initialization, the instance can be used for the intended "service". Putting the complete application code into the constructor would spoil that.

So this approach would force three different contracts upon the application:

  • There must be a default constructor. Otherwise, the JVM would not know which constructor to call and what parameters should be provided.
  • There must be a main method1. Ok, this is not surprising.
  • The class must not be abstract. Otherwise, the JVM could not instantiate it.

The static approach on the other hand only requires one contract:

  • There must be a main method1.

Here neither abstract nor multiple constructors matters.

Since Java was designed to be a simple language for the user it is not surprising that also the application entry point has been designed in a simple way using one contract and not in a complex way using three independent and brittle contracts.

Please note: This argument is not about simplicity inside the JVM or inside the JRE. This argument is about simplicity for the user.


1Here the complete signature counts as only one contract.
Celebrated answered 28/9, 2008 at 19:45 Comment(9)
Actually, the requirements are more complex: there must be a main method which is public, static, and has the signature void main(String[]). I agree that, if the method were an instance method, the JRE would have slightly more work but the kind of work would be the same, and the complexity not significantly higher (see discussions in comments of previous answer). I do not believe that this difference accounts for the decision to make the entry point static, in particular since the required methods for the resolution of an instance method exist, and are readily usable.Oniskey
@KonradRudolph: My point is not about the work the JRE would have to do. My point is about forcing every user of the language to follow more contracts as necessary. In this sense a static public main(String[]) method is one signature and hence one contract. Otherwise three independent contracts must be followed.Celebrated
Ah. I still disagree that this makes any difference though. Entry point classes could well implement Runnable. Clearly, Java expects developers to follow that contract all the time, why should it be too much for the application entry point? That makes no sense.Oniskey
@KonradRudolph: Because the instance of Runnable is created by the user and not by the system. Hence contract #1 and #3 are not required for Runnable.Celebrated
@KonradRudolph Even if the magnitude of the complexity is not significant, an instance method is more complex. In that case, complexity is a reasonable justification for choosing static.Myocardiograph
@Celebrated Now you are contradicting yourself, I thought you objected to the fact that user, not the system has to work against fixed contracts. Be that as it may, the requirements in both cases are the same, for the system as for the user: the user has to abide by the contracts, the system has to enforce them.Oniskey
@KonradRudolph: There is no contradiction: In one case the system would force three contracts upon the user. Contracts which are dubious, which are not checkable via the compiler and which are, from the user's point of view, independent. In the usual Thread and Runnable case nothing is hidden from the user, he can clearly see what's going on and he has the change to implement only those contracts which suit him - he is in control, not the system.Celebrated
@Celebrated Now I see what you’re saying. I need to think about whether this convinces me.Oniskey
This is the best answer here. It's a shame that many users will only read the top 2 or 3 answers on the page; and this one is unlikely to get there any time soon. It mentions the important point of a constructor being ONLY for initialisation - and therefore it makes no sense to code in a style where the constructor runs the entire application.Rosarosabel
R
41

Why public static void main(String[] args) ?

This is how Java Language is designed and Java Virtual Machine is designed and written.

Oracle Java Language Specification

Check out Chapter 12 Execution - Section 12.1.4 Invoke Test.main:

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either

public static void main(String[] args)

or

public static void main(String... args)

Oracle Java Virtual Machine Specification

Check out Chapter 2 Java Programming Language Concepts - Section 2.17 Execution:

The Java virtual machine starts execution by invoking the method main of some specified class and passing it a single argument, which is an array of strings. This causes the specified class to be loaded (§2.17.2), linked (§2.17.3) to other types that it uses, and initialized (§2.17.4). The method main must be declared public, static, and void.

Oracle OpenJDK Source

Download and extract the source jar and see how JVM is written, check out ../launcher/java.c, which contains native C code behind command java [-options] class [args...]:

/*
 * Get the application's main class.
 * ... ...
 */
if (jarfile != 0) {
    mainClassName = GetMainClassName(env, jarfile);

... ...

    mainClass = LoadClass(env, classname);
    if(mainClass == NULL) { /* exception occured */

... ...

/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                                   "([Ljava/lang/String;)V");

... ...

{    /* Make sure the main method is public */
    jint mods;
    jmethodID mid;
    jobject obj = (*env)->ToReflectedMethod(env, mainClass,
                                            mainID, JNI_TRUE);

... ...

/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
    ReportExceptionDescription(env);
    goto leave;
}

/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

... ...
Resurrection answered 28/9, 2008 at 19:45 Comment(5)
The problem here is that this is actually a very good answer to the question in its original form, with plenty of references (+1). However, I’d love to learn about the rationale for the design decision of making a static method the entry point, rather than a constructor or instance method.Oniskey
@KonradRudolph, for questions regarding to language and JVM specification design, perhaps you could try contact original source from Oracle and see if you can get any positive feedback.Resurrection
Generally speaking when a method result computation depends only on its parameters, so that it does not depend on the object instance internal state, it can be static. And it is recommended to set it as static for code maintainability/re-usability. If the method main was not static, it means the class instance state must be known and it is much more complex to define, like which constructor to use first.Phenoxide
@KonradRudolph Interestingly, Oak (the predecessor of Java) already required the main method to have a similar prototype: public static void main(String arguments[]) - Reference: Oak 0.2 Spec.Foulk
@Yves It can be. It needn’t, if another design makes sense. I’ve heard some good arguments in the comments here but I still think that a process is effectively very much like a thread (it is), and a thread in Java is usually represented as an instance of Runnable. Representing the whole process in the same way (i.e. having Runnable.Run as the entry point) definitely makes sense in Java. Of course, Runnable itself is arguably a design flaw, caused by the fact that Java doesn’t have anonymous methods (yet). But since it’s there already …Oniskey
T
14

If it wasn't, which constructor should be used if there are more than one?

There is more information on the initialization and execution of Java programs available in the Java Language Specification.

Tang answered 28/9, 2008 at 19:45 Comment(0)
C
13

Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first.

Custom answered 28/9, 2008 at 19:45 Comment(2)
Wrong. Or at least very unprecise. public class Main { static Object object = new Object() { { System.out.println("object created"); } }; public static void main(String[] args) { System.out.println("in main"); } }Cardiogram
Fair comment. Technically, I should have said that before the Main method is called, the class containing the main method is not instantiated.Custom
F
12

Let me explain these things in a much simpler way:

public static void main(String args[])

All Java applications, except applets, start their execution from main().

The keyword public is an access modifier which allows the member to be called from outside the class.

static is used because it allows main() to be called without having to instantiate a particular instance of that class.

void indicates that main() does not return any value.

Faefaeces answered 28/9, 2008 at 19:45 Comment(0)
P
12

Because otherwise, it would need an instance of the object to be executed. But it must be called from scratch, without constructing the object first, since it is usually the task of the main() function (bootstrap), to parse the arguments and construct the object, usually by using these arguments/program parameters.

Pain answered 28/9, 2008 at 19:45 Comment(0)
S
11

What is the meaning of public static void main(String args[])?

  1. public is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine.
  2. static allows main() to be called before an object of the class has been created. This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class.

    class demo {    
        private int length;
        private static int breadth;
        void output(){
            length=5;
            System.out.println(length);
        }
    
        static void staticOutput(){
            breadth=10; 
            System.out.println(breadth);
        }
    
        public static  void main(String args[]){
            demo d1=new demo();
            d1.output(); // Note here output() function is not static so here
            // we need to create object
            staticOutput(); // Note here staticOutput() function is  static so here
            // we needn't to create object Similar is the case with main
            /* Although:
            demo.staticOutput();  Works fine
            d1.staticOutput();  Works fine */
        }
    }
    

    Similarly, we use static sometime for user defined methods so that we need not to make objects.

  3. void indicates that the main() method being declared does not return a value.

  4. String[] args specifies the only parameter in the main() method.

    args - a parameter which contains an array of objects of class type String.

Sheelah answered 28/9, 2008 at 19:45 Comment(0)
E
6

Applets, midlets, servlets and beans of various kinds are constructed and then have lifecycle methods called on them. Invoking main is all that is ever done to the main class, so there is no need for a state to be held in an object that is called multiple times. It's quite normal to pin main on another class (although not a great idea), which would get in the way of using the class to create the main object.

Episiotomy answered 28/9, 2008 at 19:45 Comment(0)
B
6

It's just a convention, but probably more convenient than the alternative. With a static main, all you need to know to invoke a Java program is the name and location of a class. If it weren't static, you'd also have to know how to instantiate that class, or require that the class have an empty constructor.

Beckerman answered 28/9, 2008 at 19:45 Comment(3)
It's not a convention; it's part of the language specification; the runtime won't recognise a class without a static main method as a valid entry point.Hollins
The language spec itself follows the convention. There is no actual requirement for the Java designers to have opted for requiring a static main. However, as Logan explains, the alternatives are more complicated.Zingaro
@DavidArno It would make more sense to say that the convention follows the language specification.Cretin
T
5

When you execute the Java Virtual Machine (JVM) with the java command,

java ClassName argument1 argument2 ...

When you execute your application, you specify its class name as an argument to the java command, as above

the JVM attempts to invoke the main method of the class you specify

—at this point, no objects of the class have been created.

Declaring main as static allows the JVM to invoke main without creating an instance of the class.

let's back to the command

ClassName is a command-line argument to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings (separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args in the main

References:Java™ How To Program (Early Objects), Tenth Edition

Tonsillectomy answered 28/9, 2008 at 19:45 Comment(0)
P
5

If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?

Parameter answered 28/9, 2008 at 19:45 Comment(0)
C
3

Recently, similar question has been posted at Programmers.SE

  • Why a static main method in Java and C#, rather than a constructor?

    Looking for a definitive answer from a primary or secondary source for why did (notably) Java and C# decide to have a static method as their entry point – rather than representing an application instance by an instance of an Application class, with the entry point being an appropriate constructor?

TL;DR part of the accepted answer is,

In Java, the reason of public static void main(String[] args) is that

  1. Gosling wanted
  2. the code written by someone experienced in C (not in Java)
  3. to be executed by someone used to running PostScript on NeWS

https://static.mcmap.net/file/mcmap/ZG-AbGLDKwfpKnMAWVMrKmltX1ywKmMva3/qcmzP.png

 
For C#, the reasoning is transitively similar so to speak. Language designers kept the program entry point syntax familiar for programmers coming from Java. As C# architect Anders Hejlsberg puts it,

...our approach with C# has simply been to offer an alternative... to Java programmers...

...

Culberson answered 28/9, 2008 at 19:45 Comment(0)
P
3

main() is static because; at that point in the application's lifecycle, the application stack is procedural in nature due to there being no objects yet instantiated.

It's a clean slate. Your application is running at this point, even without any objects being declared (remember, there's procedural AND OO coding patterns). You, as the developer, turn the application into an object-oriented solution by creating instances of your objects and depending upon the code compiled within.

Object-oriented is great for millions of obvious reasons. However, gone are the days when most VB developers regularly used keywords like "goto" in their code. "goto" is a procedural command in VB that is replaced by its OO counterpart: method invocation.

You could also look at the static entry point (main) as pure liberty. Had Java been different enough to instantiate an object and present only that instance to you on run, you would have no choice BUT to write a procedural app. As unimaginable as it might sound for Java, it's possible there are many scenarios which call for procedural approaches.

This is probably a very obscure reply. Remember, "class" is only a collection of inter-related code. "Instance" is an isolated, living and breathing autonomous generation of that class.

Pasteboard answered 28/9, 2008 at 19:45 Comment(1)
This is incorrect. Plenty of objects are instantiated before main is reached. And if you include a static constructor in the class containing main, that gets executed before main likewise.Oniskey
R
3

I think the keyword 'static' makes the main method a class method, and class methods have only one copy of it and can be shared by all, and also, it does not require an object for reference. So when the driver class is compiled the main method can be invoked. (I'm just in alphabet level of java, sorry if I'm wrong)

Roche answered 28/9, 2008 at 19:45 Comment(1)
All methods 'have only one copy of it'.Cretin
E
3

It is just a convention. The JVM could certainly deal with non-static main methods if that would have been the convention. After all, you can define a static initializer on your class, and instantiate a zillion objects before ever getting to your main() method.

Exuberant answered 28/9, 2008 at 19:45 Comment(0)
E
2

The protoype public static void main(String[]) is a convention defined in the JLS :

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

In the JVM specification 5.2. Virtual Machine Start-up we can read:

The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java virtual machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.

Funny thing, in the JVM specification it's not mention that the main method has to be static. But the spec also says that the Java virtual machine perform 2 steps before :

Initialization of a class or interface consists of executing its class or interface initialization method.

In 2.9. Special Methods :

A class or interface initialization method is defined :

A class or interface has at most one class or interface initialization method and is initialized (§5.5) by invoking that method. The initialization method of a class or interface has the special name <clinit>, takes no arguments, and is void.

And a class or interface initialization method is different from an instance initialization method defined as follow :

At the level of the Java virtual machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name <init>.

So the JVM initialize a class or interface initialization method and not an instance initialization method that is actually a constructor. So they don't need to mention that the main method has to be static in the JVM spec because it's implied by the fact that no instance are created before calling the main method.

Earpiece answered 28/9, 2008 at 19:45 Comment(0)
A
2

The true entry point to any application is a static method. If the Java language supported an instance method as the "entry point", then the runtime would need implement it internally as a static method which constructed an instance of the object followed by calling the instance method.

With that out of the way, I'll examine the rationale for choosing a specific one of the following three options:

  1. A static void main() as we see it today.
  2. An instance method void main() called on a freshly constructed object.
  3. Using the constructor of a type as the entry point (e.g., if the entry class was called Program, then the execution would effectively consist of new Program()).

Breakdown:

static void main()

  1. Calls the static constructor of the enclosing class.
  2. Calls the static method main().

void main()

  1. Calls the static constructor of the enclosing class.
  2. Constructs an instance of the enclosing class by effectively calling new ClassName().
  3. Calls the instance method main().

new ClassName()

  1. Calls the static constructor of the enclosing class.
  2. Constructs an instance of the class (then does nothing with it and simply returns).

Rationale:

I'll go in reverse order for this one.

Keep in mind that one of the design goals of Java was to emphasize (require when possible) good object-oriented programming practices. In this context, the constructor of an object initializes the object, but should not be responsible for the object's behavior. Therefore, a specification that gave an entry point of new ClassName() would confuse the situation for new Java developers by forcing an exception to the design of an "ideal" constructor on every application.

By making main() an instance method, the above problem is certainly solved. However, it creates complexity by requiring the specification to list the signature of the entry class's constructor as well as the signature of the main() method.

In summary, specifying a static void main() creates a specification with the least complexity while adhering to the principle of placing behavior into methods. Considering how straightforward it is to implement a main() method which itself constructs an instance of a class and calls an instance method, there is no real advantage to specifying main() as an instance method.

Alexandra answered 28/9, 2008 at 19:45 Comment(1)
This is just begging the question. Java needs an application loader anyway which does heavy lifting before calling main. Your rationale about main being too complex for beginners seems unbelievable. In fact, the static main is very confusing for beginners, I doubt a constructor would be more so. You say a “constructor should not be responsible for the object’s behaviour”. This sounds interesting but I’m not sure I’d agree. Why doesn’t it? What prevents this?Oniskey
F
2

The public keyword is an access modifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared.

The opposite of public is private, which prevents a member from being used by code defined outside of its class.

In this case, main() must be declared as public, since it must be called by code outside of its class when the program is started.

The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by the Java interpreter before any objects are made.

The keyword void simply tells the compiler that main() does not return a value.

Fadeout answered 28/9, 2008 at 19:45 Comment(0)
P
1

static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.

Pyrenees answered 28/9, 2008 at 19:45 Comment(0)
C
1

I don't know if the JVM calls the main method before the objects are instantiated... But there is a far more powerful reason why the main() method is static... When JVM calls the main method of the class (say, Person). it invokes it by "Person.main()". You see, the JVM invokes it by the class name. That is why the main() method is supposed to be static and public so that it can be accessed by the JVM.

Hope it helped. If it did, let me know by commenting.

Curren answered 28/9, 2008 at 19:45 Comment(0)
A
1

The public static void keywords mean the Java virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static), and the program does not return data to the Java VM interpreter (void) when it ends.

Source: Essentials, Part 1, Lesson 2: Building Applications

Apollonian answered 28/9, 2008 at 19:45 Comment(0)
L
0

main method always needs to be static because at RunTime JVM does not create any object to call main method and as we know in java static methods are the only methods which can be called using class name so main methods always needs to be static.

for more information visit this video :https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be

Lorusso answered 28/9, 2008 at 19:45 Comment(0)
T
0

The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.

Telford answered 28/9, 2008 at 19:45 Comment(0)
F
0

there is the simple reason behind it that is because object is not required to call static method , if It were non-static method, java virtual machine creates object first then call main() method that will lead to the problem of extra memory allocation.

Franke answered 28/9, 2008 at 19:45 Comment(0)
F
0

Basically we make those DATA MEMBERS and MEMBER FUNCTIONS as STATIC which are not performing any task related to an object. And in case of main method, we are making it as an STATIC because it is nothing to do with object, as the main method always run whether we are creating an object or not.

Footling answered 28/9, 2008 at 19:45 Comment(0)
F
0

Any method declared as static in Java belongs to the class itself . Again static method of a particular class can be accessed only by referring to the class like Class_name.method_name();

So a class need not to be instantiated before accessing a static method.

So the main() method is declared as static so that it can be accessed without creating an object of that class.

Since we save the program with the name of the class where the main method is present( or from where the program should begin its execution, applicable for classes without a main() method()(Advanced Level)). So by the above mentioned way:

Class_name.method_name();

the main method can be accessed.

In brief when the program is compiled it searches for the main() method having String arguments like: main(String args[]) in the class mentioned(i.e. by the name of the program), and since at the the beginning it has no scope to instantiate that class, so the main() method is declared as static.

Fecundate answered 28/9, 2008 at 19:45 Comment(1)
It happens when the program is executed, not compiled.Cretin
C
0

From java.sun.com (there's more information on the site) :

The main method is static to give the Java VM interpreter a way to start the class without creating an instance of the control class first. Instances of the control class are created in the main method after the program starts.

My understanding has always been simply that the main method, like any static method, can be called without creating an instance of the associated class, allowing it to run before anything else in the program. If it weren't static, you would have to instantiate an object before calling it-- which creates a 'chicken and egg' problem, since the main method is generally what you use to instantiate objects at the beginning of the program.

Cowcatcher answered 28/9, 2008 at 19:45 Comment(12)
But it does not run “before anything else in the program”. The whole argument is a fallacy, and what’s more, this isn’t the first answer mentioning it, nor even the second or third.Oniskey
I'm sorry that my answer repeats what others have said; I only answered to the best of my understanding and from what I could find online. From the results that I've looked at there is no other reason as to why the main method is static; unless there's one deeply hidden somewhere perhaps that's the only answer there is. My understanding of Java is fairly basic, but I have heard the above reason (from professors, textbooks, etc) and never any other.Cowcatcher
@Jesse M Your comment only makes sense if you didn't even consider reading the other answers first. Which by the way is not a far fetched thing to do. As you mentioned yourself, your understanding is fairly basic so it is very probable that somebody else already answered the question more competently. And your comment seems to be an rationalization in order to make your answer look better. It's an extraordinary claim that you have Java textbooks and professors that think what you claim and frankly I don't believe they do. (Any references?)Acaleph
@KonradRudolph The top comments seem pretty reasonable. main() is used as an entry point to the program and there are several references on the Java website saying that it is supposed to be similar to how C/C++ have a main() function. Because Java is all Objects, it has to be static to avoid object instantiation. Having it static also lets it be loaded and executable into the JVM at runtime. I'm just regurgitating previous answers, but I'm wondering what you would consider a satisfying answer. I think the best you will get is "That's how they wanted it". Keep in mind the date Java was made.Septum
@Atlos Your reasons are not actually explanations: you say “it has to be static to avoid object instantiation” but why do you want to avoid object instantiation in the first place? This is the real question here.Oniskey
@KonradRudolph Avoiding object instantiation isn't much of a problem today, but when Java came out I see it being a memory and speed issue. Java was initially targeted for consumer digital electronics in the early 90's and I could imagine the restrictions they had to deal with. Java was competing with C/C++ in that market specifically. I'm just piecing both ideas together, so no "hard proof" like you want, but I think it makes the most sense. Your best chance is to email Sun Microsystems and ask a design engineer.Septum
@Atlos I don’t buy that. It’s a one-time thing, it takes less then a microsecond. Even when Java came out. It probably wouldn’t even be measurable.Oniskey
@Acaleph I admit that I was at fault by not reading all of the other answers first; I wasn't aware to what extent my answer had been repeated. The reason I felt confident enough to answer the question was that I've never had to think 'deeply' about this issue before; when I said that I had heard the statement made by professors, I was conveying the fact that this was simply what I'd been taught. I can't quote when or where exactly I learned this for the same reason I can't tell you when I learned about for loops; I've always taken the reasoning for granted.Cowcatcher
I also don't see why it's such an extraordinary claim. You said yourself that all the other answers were the same as mine; so why is it unreasonable that this is a commonly held belief that many people have learned or been taught? I have no reason to lie about what I learned, unless I was that desperate for Konrad's bounty-- which I knew I wasn't getting, since many of the answers were longer and more elaborate than mine. Which brings up the main reason that I answered the question at all:Cowcatcher
@KonradRudolph Is it possible that the answer you're looking for simply doesn't exist? Yes, object instantiation takes an extremely small amount of time, but does that mean that it makes sense to force programmers to do it when it's not necessary? Why can't the reasoning be the same as with any other static method? As far as I know, you could accomplish the same goals not using static methods as by using them in any program. But when a method isn't logically related to a particular class, there is the option not to associate it with a class.Cowcatcher
I don't see why it can't just be a matter of convention, readability and choice on the programmer's side. If that's not a sufficient answer, then perhaps you should contact Sun as Atlos recommended.Cowcatcher
@Jesse Spot-on. It’s entirely possible that it’s merely a matter of convention (although I hope that it’s not, that would be such a boring answer). My original interest in this question was because I thought that using a proper instance to represent the object “running application”, and having the entry point be a method (or the constructor) of this class would be a much more obvious design, since Java was designed to be object oriented from the get-go, and since seemingly analogous objects (threads, via Runnable) in Java do use this design. Why the (apparent) exception here?Oniskey
M
0

It is just a convention as we can see here:

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. By default, the first non-option argument is the name of the class to be invoked. A fully-qualified class name should be used. If the -jar option is specified, the first non-option argument is the name of a JAR archive containing class and resource files for the application, with the startup class indicated by the Main-Class manifest header.

http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description

Medlin answered 28/9, 2008 at 19:45 Comment(1)
Rule of the language, you mean.Cretin
M
0

The static key word in the main method is used because there isn't any instantiation that take place in the main method. But object is constructed rather than invocation as a result we use the static key word in the main method. In jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.

Metrics answered 28/9, 2008 at 19:45 Comment(0)
G
0

Static methods don't require any object. It runs directly so main runs directly.

Grebe answered 28/9, 2008 at 19:45 Comment(0)
R
-1

It's a frequently asked question why main() is static in Java.

Answer: We know that in Java, execution starts from main() by JVM. When JVM executes main() at that time, the class which contains main() is not instantiated so we can't call a nonstatic method without the reference of it's object. So to call it we made it static, due to which the class loader loads all the static methods in JVM context memory space from where JVM can directly call them.

Righteous answered 28/9, 2008 at 19:45 Comment(1)
This answer was first given in September 2008. The question has been answered. You're not adding any value here.Cretin
B
-1

As the execution start of a program from main() and and java is purely object oriented program where the object is declared inside main() that means main() is called before object creation so if main() would non static then to call it there would be needed a object because static means no need of object..........

Boat answered 28/9, 2008 at 19:45 Comment(0)
E
-1

static indicates that this method is class method.and called without requirment of any object of class.

Elea answered 28/9, 2008 at 19:45 Comment(0)
P
-5

because, a static members are not part of any specific class and that main method, not requires to create its Object, but can still refer to all other classes.

Pottery answered 28/9, 2008 at 19:45 Comment(1)
Answer is very misleading.Skirmish

© 2022 - 2024 — McMap. All rights reserved.