I still don't understand public static void main(string [ ] args) [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
After almost 1 year working with Java,I still can not explain properly to others or myself why we need this, and how it works.
Obviously, I know what each of keywords does independantly, but I am not sure about the whole thing.
Can someone please describe it in very simple language?

Public : is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only.
String args[] : is the parameter to the main Method.

The other answers are correct, but I'll try to state it in English.
When you create a program, java needs to know where to start the program, so they use this as an entry point. Since it's static method, there doesn't need to be an instantiation of the class. It can simply call that method and know that that's where the program starts.

I knew these already thank you for you response and downvotes.
public
It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in you current class.
static
When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
void
Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
main
It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
String args[]
These are the arguments of type String that your Java application accepts when you run it.
But why there is no simplar method to call main like in other languages, and why we need to get argument and store as String while we sometimes only call methods in the main.

When you start a Java program the JVM needs to know where it should start the execution of the whole thing. This is not obvious because there are thousands of Java classes available on the classpath.
That's why you must give the name of one particular Java class in your command line. For example
java com.stackoverflow.example.Main bla blah
The JVM then just loads this class, looks for its static void main(String[] args) method, and calls it with the remaining parameters taken from the command line
main(new String[]{"bla", "blah"});

The main() method is defined by the java launcher:
The java command starts a Java application. It does this by starting the Java Runtime Environment (JRE), loading the specified class, and calling that class's main() method. The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:
public static void main(String[] args)
That explain why you need it: It's required to start running a Java program.
And how it works: It's called by the launcher at startup.

Related

Java compilation of methods [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to understand the Java compiler better, and what is happening behind the scenes during compilation and execution, and so I have a question about how Java methods are compiled.
I know that methods need to be called upon or invoked in order for their enclosing code to be executed, and I just want to figure out how this really works
Considering the simple program:
public class Test {
public static void sayHello() {
System.out.println("Hello World");
}
public static void main(String []args){
sayHello();
}
}
Considering that code in java is executed in the order that it appears, why would the contents of sayHello() not be executed, but instead the program waits until the method is invoked for the contents of the method to be executed? So basically I'm asking how does the compiler deal with compiling methods, and what does it do to prevent methods from the contents of a method being run sequentially without them being called on?
Thank you.
Your assertion, "Considering that code in java is executed in the order that it appears", was refuted in comments. However, there is one way in which you could say there is some truth to it, as long as you interpret your statement in a specific way. Let's look at your class:
public class Test {
Here, you're asking the compiler to create a class, and store it in file Test.class.
public static void sayHello() {
This tells the compiler to define a method called sayHello.
System.out.println("Hello World");
This declares to the compiler that this is the content of the method, and to store this content for execution when the method is called.
}
public static void main(String []args){
sayHello();
This tells the compiler to call the method sayHello whenever the method main is called and its body starts getting executed. The method main is called when you run the application with the java command line.
}
}
You see, in a way the contents are "executed" (for some unusual definition of executed) in the order they appear. But that doesn't mean they are run at that time.
The main() function will almost always be executed first.
It is the function that actually contains the code that is run.
Normally you put main() at the top and other functions below it.

Calling a Java Method using ProcessBuilder [duplicate]

This question already has answers here:
Can I invoke a java method other than main(String[]) from the command line?
(8 answers)
Closed 2 years ago.
We know that JVM looks for main() method during class execution. Can we customize JVM to execute our own custom function instead of main method by default?
if yes, how do we do it?
You can do this by implementing a native custom launcher as described here:
http://www2.sys-con.com/itsg/virtualcd/java/archives/0709/chamberlain/index.html
But frankly, it is not worth the effort if you simply want to use a different convention for the entry point. A simpler approach is to write a "proxy" entry point class with a conventional main method, have that find / load / call your "real" entry point.
On the other hand, if your goal is to execute some code before the main method gets called, one trick is to put the code into a static initializer block in the entry point class. For example:
public class Entry {
static {
System.out.println("Hello world");
}
public static void main(String[] args) {
// ...
}
}
will print "Hello world" before the main method is called.
Speculation! It might also be possible identify the hidden Java bootstrapping class that finds / loads / calls the normal entrypoint class. Then you could replace it by adding a modified version to the bootstrap classpath. However, you will be straying into dangerous territory. Interference with hidden mechanisms is liable to end badly if you get it wrong.
No. The main(String[]) method is the Java entry point. You can package your application as a jar then you can set the Main-Class and run it like java -jar myapp.jar. See also Setting an Application's Entry Point. That being said, any static initialization blocks will run before main. But you get an exception if the class specified doesn't have a main method. The only other exceptions I can think of are Servlets and (the almost dead) Applets.

JAVA Why should a non public class be executable; isn't it being used outside its package? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In Java, I can a run/execute a non public (i.e. 'default' access) java class from the command line even though it is in a package. Why should this be possible? are we not thereby using a default class outside its package which is not supposed to be correct?
I think you're describing something like the following (See Is a class private or public by default in Java and C++? about the available visibility modifiers on a java class):
class PkgPrivateClass {
public void doIt() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
PkgPrivateClass pkgPrivateClass = new PkgPrivateClass();
pkgPrivateClass.doIt();
}
}
This compiles and prints Hello World!.
Now for the question what is accessible and why:
The main method doesn't and can't do anything other than every static method.
The main method is only visible inside the same package (as the class is package private). Starting a java program - i.e. calling the main method - is hardly comparable to an ordinary method call within a java program.
While package private classes are anyway not used that often (see Pros and cons of package private classes in Java?), I see two arguments why it makes sense to allow calling package private classes from the command line:
You explicitly added the public static void main(String[] args) method. If you don't want this class to be called, you don't add this method.
When starting the JVM, you usually give the fully qualified class name. One could argue that this makes the command line call executed from this package - or asked the other way around: From what package is a main method called?
The access modifier default has another name which is called as package specific.
So if you are in the same package for a default class you can use command line execution. Outside the package you can not execute default class directly.
main() invoked via reflection, that ignores class visibility. You can write own executor instead of java.exe, that will check class visibility too, or do NOT check visibility of main() for example.

Why does Java Specifications want the main method of a program to be void only? [duplicate]

This question already has answers here:
Why is main() in java void?
(4 answers)
Closed 7 years ago.
Although the return type is not a part of a method's signature, JVM looks for exact declaration as
public static void main(String[] args)
My assumption is that since method signature does not have "return type" included, I must be
allowed to change the return type.
But if I change it to public static int main(String[] args) and return a value lets say 0, JVM is not able to execute the program and exits with an error
Error: Main method must return a value of type void in class TestData, please
define the main method as:
public static void main(String[] args)
Why do Java Specifications want the main method to be void only?
Why is this restriction, when return type is not a part of method signature?
This question is different than Why is main() in java void? : this question is closed as it is opinion based, while I am looking for the code places/ processes from where JVM is invoking this method, and what are the limitations which are forcing them to keep this method as void. What are the design decisions they have taken (and the reasoning behind), and where is it documented.
I am looking for facts, so as to know the reason why is it done so.
Please don't mark it duplicate without going through the details of the question.
PS: exit, is another thing. I am more concerned about entry of the program. Also, the returned value might not be to the use of JVM, restricting it to void limits extensibility.
So far what I have learnt from this question is : Java specifications have explicitly fixed return type to avoid confusion to migrating programmers (C/CPP) who may expect this value to return to OS, but since JVM is in-between this value will never be returned to OS. For this special purpose (returning value to OS) they have provided System.exit() method.
For all those who are suggesting that return type is part of signature-- Just try to define both of the following methods in a class
public static void main(String[] a){
}
public static String main(String[] a){
}
You will get a compilation error, because signature of both of these methods is same.
The main is void is specified in JLS 12.1.4 Invoke Test.main:
The method main must be declared public, static, and void.
Sometimes the answer to a why? is because the specification says so (aka Quod Ego Dixit, or Because I Say So (Terry Pratchett)). Sometimes the decisions of a language designer are not available and the only thing we can do is guess. This is also the reason the obvious duplicate (Why is main() in java void?) is closed as primarily opinion-based.
Now as the - to me - obvious reason: JLS 12.8 Program Exit says:
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
This means that the end of the main method does not necessarily mean the end of the program. A return code from a main method has a well-known meaning in languages like C: it is the process exit code. This meaning doesn't apply when the main method may exit long before the process itself ends.
Most non-trivial Java applications have - usually- a short-lived main method that kicks off one or more long-living non-daemon threads. Allowing a return code from a Java main method could imply a meaning that is not actually there: that the return value is the process exit code. So explicitly specifying that main must have a void return type is good thing: it reduces confusion or assigning meaning that isn't there.
The main method may not be an exit point after all. Due to multi-threading it may happen that when the main returns there's still another thread on the pitch keeping the program alive. An exit code makes no sense in this case.
Why not void?
If you wish to return some status to OS you can use any of exiting methods.Most common one being System.exit(int status) .
If your main finishes before the other threads, a return value won't matter.
This is in contrast with c/c++ which do not supported multi-threading that time.
Like a swing application may still work on EDT after finishing main.
And if you are still considering the "entry" point: but the return type always talks about the exit.
So it's simply void as we have status signallers to return a value or no return in other case.
Still, there is no other point because it was designed in this way.Another developer with different thoughts might throw another idea to solve same situation.Depends.
As stated in
http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.8
12.8. Program Exit
A program terminates all its activity and exits when one of two things
happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System,
and the exit operation is not forbidden by the security manager.
the program exits, if all running threads are deamon. So if you have a non deamon thread, the main method might return before the program ends.
The lifetime of your program can extend the lifetime of the main method and the return number might be decided later in the program.
I think this is why they use System.exit() as return point.
You can't look at below from Java Docs, for your main method to serve as exit point you need to have the method void. or you have an option to call system.exit() explicitly at the end of you main.
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
As per my knowledge,
The reason for the main method having void as return type is that, once the main method finishes its execution, it doesn't mean that the entire program finished. It may have some threads initiated and running behind the scene. Even if the main thread is dead, still there is a chance of child threads to be running. In this case the return type of main doesn't make much sense.
And JVM will monitor the program completion status to deallocate the memory, Its not necessary to return something to JVM that states the program is finished. In C-language we are directly communicating with O.S. so, there is an option to return int value to O.S. that states the execution is done and start deallocating the memory. But here in java, JVM will communicate with O.S. but not the program, So we no need to return anything from main.
Hope this clears your doubt.
If you ask JVM to run a class, java runtime will look for exactly that signature in your class public static void main(String[] args)
That is your contract with the JVM, if not, it will not execute.
If you want an int code back, use System.exit
A console program returns an int return code, and thus in a traditional C program an int main(int argc, char** argv) seems logical.
In Java the exception was introduced as a new control flow mechanism, and also multi-threading was simulated or now implemented. Exit could be done everywhere with System.exit(int returnCode).
This means that the call to main is embedded in a piece of code, and cleanest (minimalistic, less cases, no magic of return 0) is to a default of returning 0, except by System.exit.
Mind, java was intended to strongly "improve" upon C and especially C++. Like having Strings and char that use full Unicode as opposed to byte.
Java has been designed as a Platform independent language. So if it's main() method returns a value (like 0 or 1 or anything), it can be interpreted or understood differently by different platform. So, unlike C and Cpp it's main() method can't return a value.
The main reason is that in common use cases particularly in multi-threading and GUI apps you don't prefer to have a return value in main. But if really you have such a use case, you can use exit method. This is the reason that you are looking for.
What is main method in Java?
Main method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet or any other container managed Java program where life cycle methods are provided to control the execution. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.
Signature of main method in Java
Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run. Here is the exact signature of main method:
public static void main(String args[])
This signature is classic signature and there from start of Java but with introduction of variable argument or varargs in Java5 you can also declare main method in Java using varargs syntax as shown in below example:
public static void main(String... args)
Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.
Why main method is static in Java
why main method is public static void in JavaNow come to the main point "Why main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:
Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
Why main mehtod is public in Java
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in
Java, JVM can easily access and execute it.
Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
Summary:
Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
JVM throws NoSuchMethodException:main if it doesn't find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
Main method is entry point for any Core Java program. Execution starts from main method.
4. Main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
When you see "Exception in Thread main” e.g.
Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
You can declare main method using varargs syntax from Java 1.5 onwards e.g.
public static void main(String... args)
Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified
above.
You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
I hope this has answered your question about the main method :)
Update in response to:
One small problem with your answer: Return type is not a part of
method signature.. hence, JVM must not throw the exception
"NoSuchMethodException:main" if the return type is different.
it doesn't return "NoSuchMethodException:main" if the return type is different and the return type is a part of the method signature. Take a look at this screenshot:
We can say, main method as class initilization method, since it satisfies one of the class initilization criterion; Please refer http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4, 12.4.1 section--
T is a class and a static method declared by T is invoked.
Now, as per JVM specification, return instruction is used to return from methods declared to be void, instance initialization methods, and class or interface initialization methods.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.8
Please see details about return instruction here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.10.1.9.return

Java Beginner question about String[] args in the main method

So I just tried excluding String[] args from the main method
It compiled alright !
But JVM is showing an exception
Why did it compile when String[] args HAS to be included every time ?
What is going on here ? Why won't it show a compilation error ?
typing this made me think that may be compiler did not see it as THE main method ..is that so ?
If that is the case..why not ? I mean isn't there supposed to be just one main method that MUST have String[] args as the argument ?
typing this made me think that may be
compiler did not see it as THE main
method ..is that so ?
Correct. There is no compile error because you're perfectly free to have all kinds of methods named main. But when you start the JVM and give it a "main class", then it will look for a method static public void main(String[]) in that class, and if it does not find such a method, it aborts with an exception.
This allows you to have multiple main methods in your program and is really the only thing that makes sense if you think about it: Applications can be composed from classes and JAR files from lots of different sources, written by different people at different times, so in many cases you can't really have a single, designated "main class" right from the start.
The JVM is looking for a very special main method to run. Only the signature
public static void main( String[] args )
is found. All other methods with name main are just "normal" methods.
Not every class has to have a public static void main(String[] args) method, only the one you want to run from the JVM. The result is that your class will compile with no error if it finds public static void main() but will throw an exception if you try and run it with the JVM because it can not find the entry point of the program.
Bottom line the entry point of your program must be public static void main(String[] args) which must be located in at least one of your .java files.
Note you can have multiple public static void main(String[] args) methods in your code (one per class) the advantage is you can use these to test and debug your classes individually.
To try to answer "why is it legal to compile without a proper main method" it's because not every java project is a stand alone application that can be run. Some are just libraries, where other programs will include them as jar files and use their code, but they don't "run" themselves. Others may be web applications, where they are deployed onto a web server that has already been started, only the server itself actually has a proper "main" method. The web application project is opened up and executed by it.
The compiler didn't really know at compile time that you were intending to try to run your code as a stand along application.
Java supports method overloading. This means you can have several methods with the same name, but different arguments.
Having said that, when you run java ClassName, Java looks in ClassName.class for a method with the signature public static void main (String[]) (it doesn't care what the String[] variable is named) and runs it. If it doesn't find one, Java will bomb out with the following exception:
Exception in thread "main"
java.lang.NoSuchMethodError: main
You are correct. The runtime is looking for a main method that takes a string array as a parameter, and isn't finding it.
The fact that you have a main method that doesn't take a string array is irrelevant. just like any other method, you can create multiple versions of main() that take different parameters - the runtime will just ignore them.
Isn't that overloading? It's fully legal to define a method
static void main() {
}
It's just not the entry point the JVM will be looking for.
Overloading is the ability to have multiple methods with the same name but different arguments. The compiler in fact creates a name based on the method name and the arguments.
So a main(String[]) would be called, to the compiler, something like main_String_arr, and main() would be called something like main.
You can have many methods named main, but only one can be THE main one - entry point to the program. It is the one with String[] args.
It's still a valid method. For example, you could have a static method called "main" with an int parameter if you wanted:
public static void main(int foo){}
The compiler doesn't complain because it's a valid method! It's just that, in order to run a Java program, Java looks for a static method called "main" with a single String array argument.
Yes..
The Java compiler will look for the same method signature to consider it a main
Writing any function that has the same name but another parameters will result in overloading functions..
Overloaded functions are not the same..!!
The case in C# is somehow different..
At last, you must make sure that your main is like that:
public static void main(String[] args)
You can use the compiler to compile part of an application: e.g. to make a jar file which you will call from another part of the app; or an applet that is started in a different way. Therefore the compiler cannot complain about the lack of a main(String[]) method. But trying to run the results of such a compile.
When you try to run the results of such a compile java is always looking for a specific main(String[]); if it can't find it it will throw a runtime exception. The main used to start an app must have exactly that signature.
Here's a quote from Java Tutorials/Getting Started:
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
So to be precise, the main method is defined by Java as an application entry point. Not everything is an application, and not every main method is an application entry point. Applets, for example, don't need a main, because it's started with a different mechanism.
Note also that since the introduction of varargs, you can actually declare your application entry point as follows:
public static void main(String... args)
This works because underneath the syntactic sugar, varargs in Java is implemented as arrays.
See also
Java Tutorials/Getting Started/Hello World
Java Tutorials/Command Line Arguments
Java Language Guide/Varargs
Related questions
Why is the Java main method static?
is possible to overload a main method?
Why main() in java is void?
Why do applets not need a main()?
Entry point for Java applications: main(), init(), or run()?
Important points:
Following is the signature of the main method:
public static void main(String[] args)
main method can be overloaded.
Multiple classes can contain the main method inside a single compilation unit (and so all of them will be called executable classes)
The class containing the main method may or may not be public.
By mistake, if you were to omit the static keyword (or the signature differs in any way), compilation would be done but a runtime error will occur.
From my blog:
Java: Important points about the main method

Categories

Resources