Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - Where and why JVM checks that the return type of entry method main(String args[]) is void and not anything else?

I will try to answer both, please correct me if I am wrong:

Where: If a static method is being called using Classname.method() or using reflection then it doesn’t matter even if you change the return type of the calling method, the same method will still be called.

So JVM probably checks this in one of the native methods of jvm.cpp

methodHandle m (THREAD, init_klass->find_method(vmSymbols::object_initializer_name(),> vmSymbols::void_method_signature()));

if (m.is_null()) { ------ THROW_MSG_0 ………..

Why: Although its useless to return a value from main, as java does not do anything with it but if we try to change the return type of main to int for example, JVM throws

public static int main(String[] args) { return 1;
}

java.lang.NoSuchMethodError: main Exception in thread "main"

So may be Java mandates the use of same signature for entry method main() to maintain a symmetry in all Java programs written.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From what I can gather, the reason main returns void in Java is threads.

C and C++ were both designed before multithreading was a common idiom, while threads were an integral part of Java from its conception. In any kind of non-trivial (multi-threaded) program, there is more than one thread, and so in reality your program never runs linearly from start to end of main.

Since the JVM doesn't halt execution until all non-daemon threads have finished running, returning from the main method doesn't mean your program ended.

With that in mind, void indeed seems like the most suited return type for main.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...