I have following class.
public class Test {
public static void main(Integer[] args) {
System.out.println("This is not a main");
}
public static void main(String[] args) {
System.out.println("This is the main");
}
}
In here there are two main method which are accept Integer[] and String [] as input argument. My question is how JVM always load second method as main method of this class. Why always consider input argument as array of String?
Because that's what Java always looks for. Java Language Specification, Section 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
Because Strings are what you're passing into the command line.
the 45 from
myProgram.exe 45
is not an integer. it is a string containing the characters 4 and 5
It just so happens that you can use a string like "45" to represent an integer. It's a little more difficult to do it the other way around.(for the user at least)
Since command line arguments are always Strings.
We always enter command line args as Strings. :)
Aside from what others have mentioned, you can use var-args to implement String array.
public static void main (String ...a)
For further information check this doc
http://docs.oracle.com/javase/tutorial/getStarted/application/
And also
Using int Instead Of String: public static void main (int[] args)
As others have said, the main method will always be called by the JVM with the overload that takes a string array. You are free to make other overloads to that metod if you so wish. You may even call them yourself in your code. It's just that the VM specifically looks for that one overload that takes an array of strings.
This is the only signature recognized by the JVM as THE MAIN METHOD
public static void main(String[] args)
You can have as many overloaded main method as you want BUT only the method with the above signature will be called by the jvm
Command-line arguments are arguments to the main() method which are passed to it at run-time. Since Java uses only String type command-line arguments, the JVM ignores the other main() method which passes Integer.
The signature of the main method in java is public static void main(String[] args) {} and that is what the JVM's classloader loads at the start of the program. The other main with an Integer argument won't be called unless you did it manually inside main. Try modifying your code as shown below and you'll notice that nothing will be called and your program won't print anything.
public class Test {
public static void main(Integer[] args) {
System.out.println("This is not a real main so nothing gets printed");
}
}
Btw, you can write an overloaded main method with any argument that you want. As long as the argument is not String[] or String... which are the same, nothing will start rolling the program.
Related
public static void main(String[] args)
I know conventionally the main function takes in a parameter args that contains the supplied command line arguments as an array of String objects.
I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer?
If there is a way to specify input for the main function, please provide an example.
Answer to your question: NO
Details:
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html
The java command starts a Java application. It does this by starting a Java runtime environment, loading a 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)
As you already know that is the method definition of main and you cannot change it. However, you can convert the elements within the args array to any other primitive type considering that it's in a valid format to be converted to the type on the left side of the assignment operator.
There are multiple ways to achieve this, one of which is:
int input = Integer.valueOf(args[0]);
No, your main method cannot take just a String, main method must accept an array of String using array syntax or varagrs syntax, read following JSL §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
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)
So, you can opt for either syntax but not just a String.
Just for your info you can create a method like public static void main(String args) but it wouldn't be regarded as "main" method of the class which JVM looks as the starting point. So, if you want to have a "main" method in your class then you have to choose from either of the above syntax.
Why not a String or an array of Integer?
Not an array of Integer because that array will cover only a subset of possible arguments (You can parse them and get an Integer, but you also need to check if they are Integers otherwise you'll get a NumberFormatException).
Not a string instead of a String array because it's better to have the command arguments separated instead of having them in one big string, in fact, a lot of times you need to handle the command arguments separately.
There's no alternative signature that the VM will recognize as main method. There is only one main signature allowed that is public static void main(String[] args)
I have not see main takes in any parameter other than String[] args. Why not a String or an array of Integer?
Yes, you can take any String or Integer as parameter, but that would become a different function main() method instead of the one used by java to start your program. After compilation, java search for public static void main(String[] args){} method to start with. If you change parameters then your program won't run at all. Now using array will cover only particular type of values that array can permit like int[] will only store intvalues, similarly String can have only one value, while you may want to have multiple arguments.
If there is a way to specify input for the main function, please provide an example.
Yes, there are ways to pass argument using command line(for windows) and terminal(for linux/unix).
compile your java program by using javac Filename.java
run java program along with parameters java FileName param1 param2 param3
(param1, param2, param3 are parameters that you want to pass).
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)
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.
This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 7 years ago.
How can you explain very well, to a beginner, the meaning of String args[] and the use of static in the following excerpt?
class FirstApp {
public static void main(String[] args) {
...
}
}
I would break up
public static void main(String args[])
in parts:
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 your 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.
I would point a beginner to the Wiki article on the Main function, then supplement it with this.
Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().
String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.
public static void main(string [] args)
public -its the access specifier means from every where we can access it;
static -access modifier means we can call this method directly using a class name without creating an object of it;
void- its the return type;
main- method name
string [] args - it accepts only string type of argument... and stores it in a string array
public : it is a access specifier that means it will be accessed by publically.
static : it is access modifier that means when the java program is load then it will create the space in memory automatically.
void : it is a return type i.e it does not return any value.
main() : it is a method or a function name.
string args[] : its a command line argument it is a collection of variables in the string format.
If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :
public static void main(String[] args) {
...
}
Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.
Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.
Then you can spend some time talking about meaning of these IMHO.
You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.
public static void main(String ...args) {
//...
}
I just thought I'd chip in on this one. It's been answered perfectly well by others though.
The full main method declaration should be :
public static void main(final String[] args) throws Exception {
}
The args are declared final because technically they should not be altered. They are console parameters given by the user.
You should usually specify that main throws Exception so that stack traces can be echoed to console easily without needing to do e.printStackTrace() etc.
As for Array Syntax. I prefer it this way. I suppose that it's a little bit like the difference between french and english.
In English it's "a black car", in french it's "a car black".
Which is the important noun, car, or black?
I don't like this sort of thing :
String blah[] = {};
What's important here is that it's a String array, so it should be
String[] blah = {};
blah is just a name. I personally think it's a bit of a mistake in Java that arrays can sometimes be declared in that manner.
To keep beginner attitude you can explain that all the command line is automatically split into an array of String (the String[]).
For static you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class
So main is static, because it is the only way to find it (linked in its own class) in a jar.
after you look at coding, and your job begin .
The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.
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.