I am not sure what this means, whenever before you write a code, people say this
public static void main(String[] args) {
What does that mean?
Here is a little bit detailed explanation on why main method is declared as
public static void main(String[] args)
Main method is the entry point of a Java program for the Java Virtual Machine(JVM). Let's say we have a class called Sample
class Sample {
static void fun()
{
System.out.println("Hello");
}
}
class Test {
public static void main(String[] args)
{
Sample.fun();
}
}
This program will be executed after compilation as java Test. The java command will start the JVM and it will load our Test.java class into the memory. As main is the entry point for our program, JVM will search for main method which is declared as public, static and void.
Why main must be declared public?
main() must be declared public because as we know it is invoked by JVM whenever the program execution starts and JVM does not belong to our program package.
In order to access main outside the package we have to declare it as public. If we declare it as anything other than public it shows a Run time Error but not Compilation time error.
Why main must be declared static?
main() must be declared as static because JVM does not know how to create an object of a class, so it needs a standard way to access the main method which is possible by declaring main() as static.
If a method is declared as static then we can call that method outside the class without creating an object using the syntax ClassName.methodName();.
So in this way JVM can call our main method as <ClassName>.<Main-Method>
Why main must be declared void?
main() must be declared void because JVM is not expecting any value from main(). So,it must be declared as void.
If other return type is provided,the it is a RunTimeError i.e., NoSuchMethodFoundError.
Why main must have String Array Arguments?
main() must have String arguments as arrays because JVM calls main method by passing command line argument. As they are stored in string array object it is passed as an argument to main().
According to the Java language specification, a Java program's execution starts from main() method. A main() method should follow the specific syntax, it can be explained as:
public static void main(String[] args)
public - Access specifier, shows that main() is accessible to all other classes.
void - return type, main() returns nothing.
String args[] - arguments to the main() method, which should an array of type string.
static - Access modifier. A main method should always be static, because the `main()' method can be called without creating an instance of the class.
Let us assume, we are executing a Helloworld java program.
While executing the program, we use the command
java Helloworld.
Internally, this command is converted into
Helloworld.main()
By making main() method static, JVM calls the main() method without creating an object first.
In Java your main method must always be:
public static void main(String args[])
The program execution starts with main() function, hence the main() function.
It must be public so that it is accessible to the outside environment.
The main() method is always static because, as you know that the program execution starts at main() method and there is no instance of the class containing main() method is initiated. Hence as the static method can run without need of any instance it is declared of static.
Java is platform independent, hence you may try to compile the java file on one system and try to execute the class file on another. Each machines' bit architecture may be different hence the return type of the main function must always be main().
Hope this helps.
Public = This method is visible to all other classes.
static = This method doesn't need an instance to be ran.
void = This method doesn't return anything.
main() = Main method (First method to run).
String[] = Array of strings.
args = Array name.
public --> Access specifier. Any other class can access this method.
static --> The method is bound to the class, not to an instance of the class.
void --> Return type. The method doesn't return anything.
main(String[] args) --> method name is main(). It takes an array of String's as argument. The String[] args are command line arguments.
Note: The main() method defined above is the entry point of a program, if you change the signature, then your program might not run.
Please go through this video link ->
https://youtu.be/ggsRGcA8hnQVery for a clear and to the point explanation of public static void main(String args[]) method.
Related
I just started learning java using eclipse IDE. I noticed that main method has to be static else it throws error. Because of this I have to declare many Scanner class' objects for each user-given input. Is there a way to make the main method non-static or defining main method without the static keyword in eclipse??
Is there a way to make the main method non-static or defining main method without the static keyword [...]?
No, this is part of how java works.
There is no way around it.
But it shouldn't impact your application since you can always create an instance of your main class and call another method on it:
public class X {
public static void main(String args[]) {
new X().nonStaticMain();
}
public void nonStaticMain() {
// just pretend this is your main
}
}
The main method is the first method that JVM looks for during compilation. This main method has to be executed even before the instantiation of any object of the class. so that later these instantiated objects will invoke other required methods. And hence, static will help the main to run before object instantiation. It is not possible to run the main method without the static keyword.
The answer is no.
You can have a look at these links too:
[A Closer Look at the "Hello World!" Application]
(https://docs.oracle.com/javase/tutorial/getStarted/application/index.html)
Why is the Java main method static?
I'm not asking what is (String args[]) because that was answered here: What is "String args[]"? parameter in main method Java.
My question is why is it necessary to write it while writing main()?
I had my practical exams, where I faced a problem and realized I hadn't written String args[] while writing public static void main(). But then after writing main(String args[]) the problem was solved. (How and Why I still don't know!)
On that same day I was asked in Viva I was asked - "Is it necessary to write this String args[] while writing main()?" and thanks to the error that occurred I replied "YES" but was left without answer when asked "WHY?".
So I want to know why is it necessary to write String[] args.
From Java Language Specification 12.1.4
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. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
public static void main(String... args)
(note that you can't have two main methods with String[] and String... in same class, since varargs are simply syntactic sugar which at compilation time will be replaced with arrays so you would end up with two methods handing String[] and one class can't have two methods with same name and parameters)
So when you execute command like
java YourClass foo bar
Java Virtual Machine will place foo and bar parameters in String[] array and will try to pass that array to main method which can accept it as parameter.
This method is also used when command doesn't have any arguments like
java YourType
This decision simplifies our life because we don't need to focus on handling cases where there are two entry points
one for command with arguments
and one where command doesn't have any arguments.
We can simply allow user to pass arguments but if we don't wan to handle them we can simply ignore them.
Also remember that we are allowed to have in our class any method which has proper declaration (and doesn't violate any rules inherited from superclass like widening member visibility - we can't make protected method public), so there is nothing wrong with having
public static void main(){
/*your code*/
}
But you need to realize that this method can't be used as entry point, so if you want to start your application from this method you will need to create proper main method which will execute your main() method:
public static void main(String ...){
main();
}
In Java the entry point has to be a public static void main(String[]) method. This is simply what is called when you run your class. A main() method with no arguments will not be called. If you have no arguments in your command you are merely calling main(String[]) with an array of length 0.
To address the Viva question, the parameter's identifier is used by the compiler only and can be changed, along with the alternate placement of the [] or using String... to specify an array. So it appears to be a technicality, but you can use any of the following:
public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)
public static void main(String[] custom_identifier)
public static void main(String custom_identifier[])
public static void main(String... custom_identifier)
It's for the command arguments. Without them, the JVM would have to perform a check to see if the method contains arguments before attempting to call the method, determining whether it could do main() or main(args) (two syntactically correct methods with different ways to call them)
The main method is the most significant method in your Java application with regards to launching your application as the entry point. What happens prior to this method being used is unclear. Please can someone help me understand/clarify what happens before the method is used by correcting my perception thereof based on the method signature as follows:
The JVM creates at least one Object that will access your main method. This (assumed) object attempts to access your Java application according to the API which obviously binds you to the known method signature public static void main (String[] args){}
public You can't restrict the (assumed) solitary object on the JVM from accessing your Object housing the main method completely looking at logic alone and not the API/signature?
static There are simply no objects up and running to create any other instances of objects up yet (other than the assumed JVM one) to instantiate or create objects out of yet. The static modifier implies the only possibility of accessing this method as it is not bound to an instance and can be accessed therefore 2ithout an instance. Yet again this is logic as without any objects up and running (apart from the assumed JVM one), there can't be any objects up yet to instantiate any other objects with?
args A standard across languages and applications/executables to provide ability to customize the application?|
Is this a correct and logical way to approach and understand the main method?
It's not entirely clear what you're really asking, but the JVM specification section 5.2 covers at least some of this:
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.
In an implementation of the Java Virtual Machine, the initial class could be provided as a command line argument. Alternatively, the implementation could provide an initial class that sets up a class loader which in turn loads an application. Other choices of the initial class are possible so long as they are consistent with the specification given in the previous paragraph.
The JLS section 12.1 has some other descriptions too.
The JVM invokes the main method directly - it doesn't need to create a new object to do so. Although the main method itself has to be public, the class it's declared in doesn't. For example:
public class Test {
private static class EntryPoint {
public static void main(String[] args) {
System.out.println("Hi");
}
}
}
Then execute with:
java 'Test$EntryPoint'
It prints "Hi" as expected.
No code outside the Test class has access to EntryPoint.main() other than through privileged reflection - or direct access that the JVM is clearly capable of.
java first boots up its core - java.lang, classloaders, system properties, runtime etc and then looks at what it has to do. Before the JVM is initialized there is no "java" in that process. Its just a native process and so I think it would be wrong to think in Java terms before this happens.
Now the JVM launcher would first look at pre mains, call them in order (first calling respective static blocks) then look at the main method, call that classes static block(s) if there are any; finally call the main method, passing any command line arguments to the premain and main methods.
Simple Tests:
public class Test {
static{
System.out.println("Hi static 1");
}
public static void main(String[] args) {
System.out.println("Hi main");
}
static{
System.out.println("Hi static 2 better to have 1 static block per class but you can have N ");
}
}
When you put the command like java someClassName then the flowing thing happen.
1.It load the class someClassName and execute the static block(if any)
During class loading an Object class Class will be created which will represent your class.
2.It invoke the main method using the the class name(It won't create any object of your class)
that why main method is static.
Say, file Demo.java contains source code as
public class Demo{
}
when this code is compiled as it's compile successfully as
$javac Demo.java
but when it's executed as
$java Demo
then it shows an exceptional error
Main method not found in class Demo, please define the main method as: public static void main(String[] args)
so compiler is not responsible to check whether main() method is present or not. JVM is responsible for it. JVM check for main() method with prottoype as
public static void main(Strings[] args)
Why JVM search main() method? Is it possible to change main() method into any other method main_hero()?
JVM is instructed to find main() method from inside JVM. Yes, it's possible to change main() method into main_hero() method but inside JVM you must have to instruct to search main_hero() method.
JVM{
public static void main(String[] args)
}
to
JVM{
public static void main_hero(String[] args)
}
Why public?
JVM is installed either in C or D drive so to call from anywhere public is used.
Why static?
main() method is no related to object so without existing object also JVM has to call this method. main method no way related to object.
Why void?
JVM is going to call main() method but what can JVM do with return value if main() method return. So it's meant to be void.
public static void main() & public void main() What is the difference between these two?
The former is (potentially) an entry point method (if it has a String[] argument). The latter is not.
The rule is that an entrypoint method must have the signature:
public static void main(String[])
If we ignore the question of "entrypointness", then the difference between a "static" method and a normal method is as follows:
A normal method can only be invoked on a target object, but it can access the instance variables of the target object via explicit or implicit use of this.
A static method is not invoked on a target object, and cannot access instance variables via this.
Static functions belong to the class (that is, they use no instance variables (object variables)).
public static void main(String[] args)
Because it uses the special 'main' name and is also static with string arguments, it is the entry point into your program. It can be called like this
YourClass.main(new String[] {"hello"})
However, when you compile you program into a runnable .jar file java will automatically know to run this method. It is the starting point of your program.
In the terminal you will run it like this
java -jar YourClass.jar hello
Other methods can also be made static
public static void myOtherFunction()
The difference here is that myOtherFunction() is NOT the starting point of the application but can be used anywhere in your application that you main need it, you also don't need an instance of a class to use it.
public void main()
Is a normal methods of a class It needs an instance to be able to use it.
YouClass me = new YouClass();
me.main();
Don't ever call any method main() without it being of the signature
public static void main(String[] args)
ie. the entry point of the application. This could potentially be confusing for people reading your code.
Static means that the function does not need a class instance in order to be called.
It's simple: the former main is static (and p in lowercase ;-P)
And the meaning is obvious: ensuring the entrypoint exists before the rest, and tell the framework where the entrypoint is.
Actually static allows only one instance of he main function to be initialized. All static methods can be called without creating an instance of that class. Its global. Main is always delcared static.
varargs version:
public static void main(String... args) {
for (String arg : args) {
System.out.println("Argument: " + arg);
}
}
Available since Java 5.
is possible to overload a main method? If yes from which method the jvm will start executing?
You can overload the main method, but the JVM would always start the main method with the following signature:
public static void main(String[] args);
As said by others, very much possible But, the execution will always start from
public static void main(String[] args)
A small program to demonstrate:
public class Test{
public static void main(String [] args){
System.out.println("First");
main();
}
public static void main(){
System.out.println("Second");
}
}
Output:
First
Second
Yes. The main method can be overloaded just like any other method in Java.
The usual declaration for main is
public static void main(String[] args) throws Exception;
When you launch a java application it looks for a static method with the name 'main', return type 'void' and a single argument of an array of Strings. ie what you throw is unimportant in resolving this method.
Overloading is providing multiple methods with the same name but different arguments (and potentially return type).
With the above explaination we can overload the main method.
Yes. You can overload the main method, but the method below will be execute when you execute the class :
public static void main(String[] args)
According to the Java Language Spec:
The method main must be declared
public, static, and void. It must
accept a single argument that is an
array of strings.
http://java.sun.com/docs/books/jls/third_edition/html/execution.html (12.1.4)
So, only the public static void main(String[] args) of your overloads will be executed.
A main method with String as its arguments is the default entry point into a program.
You can Overload but it would not change the entry point of the program.
Yes you can. The jvm is smart enough to know which one to load as it looks at the method declaration that matches your main method and is logical. The parts of the main method declaration make perfect sense when you think like the 'jvm' and picture what the main method does (starts the application):
public, because this method must be accessible by the jvm (not written by you).
static, implying this method can be accessed without having an object (because it's representation never changes), but here the logic is easily understood if you think like the jvm again; "I don't have any objects to create (instantiate) objects, so I need a static method to start the application as there simply isn't any logical way to get an instance specific method up yet as I don't have anything up yet to create objects".
void This method can't logically return anything because there is nothing up yet to return anything to. It is the start point of the application.
main I am the main method as without me you won't have an application.
String[] args Send me data you may feel useful for my start up.