What is the difference between these 4 method signatures, and why does the 4th not work?
public void main(String args[]) {... }
public void main(String[] args) {... }
public void main(String... args) {... }
public void main(String[] args[]) {... }
The first three are equivalent.* The last one is equivalent to String[][] args (i.e. an array of arrays), which doesn't match what Java requires for main.
However, the idiomatic version is the second one.
* The third one is only valid from Java 5 onwards.
String args[] and String[] args are exactly equivalent. The first form is the "C" form of array declaration, with the [] applied to the variable name. The second form is the preferred Java form, where the [] is (more logically) associated with the type name rather than the variable name. Java allows both forms interchangeably.
The third form appears to be a variable-length parameter list form, though I've never delved into that area.
The forth form is an abomination that only sneaks through the cracks of the spec and should never be used. My guess is that it specifies a 2-dimensional array, but one can't be sure without trying it.
Note that there's nothing sacred about public static main. You can name any method main and call it from anywhere. It's just that when you run a Java program from the command line the JAVA command looks for something of that name (with the usual parameter layout) as the entry point. Up until then main is treated like any other method.
Related
Can some one tell , why args in main method are of String type . in
public static void main(String args[]){
}
I mean, why it is not int or float or something else. I was asked the same but could not find appropriate answer.
You might run your java program with parameters through console like this:
java YourClass first second third
In the java program you may use it through String args[].
public static void main(String[] args) {
Arrays.asList(args).forEach(System.out::println);
}
Output:
first
second
third
But it is not necessary to use such name. There are few ways to declare signature of the main method:
public static void main(String... args)
public static void main(String[] strings)
public static void main(String [] args)
Why it is not int or float or something else? At the command prompt the command is considered to be a string.
I will give you my inputs.
Command line arguments are Strings which is why that is the data type.
You can get other datatypes easily from Strings.
Most of Java's syntax is based on C, and since C used String args, maybe the creators did the same for java. (Just a possibility)
when we write java filename.java that means you giving your filename to java compiler whose main method is to be called it is obvious that the file name you are giving will be a string.
on the other end if you want to give any parameter to compiler at the same time it will also be in string not an integer or any other data type.
Because String can be converted to any type easily. If it were int and you want to take double as input, how would this happen? But with String, you can convert to whatever you expect.
I was trying to call the main function inside the main function i have tried the following code and got successfully compiled code.
class test
{
static int i = 0;
public static void main(String args[])
{
String asda[] = {"!2312"};
if (++i == 1)
main(asda);
}
}
But the error occurs in case of the following code:
class test
{
static int i = 0;
public static void main(String args[])
{
if (++i == 1)
main({"!2312"});
}
}
this made me so confused. the confusion is that String array initialization is done like String A[]={"asdf","Asdf"); then why is it giving an error in the second case?
I'm using java 8u40.
The syntax for what you're looking for is:
main(new String[]{"!2312"});
In your first example, Java is smart enough to know that you're creating a String array, since it's in the String[] declaration part. But since you don't have that in your second example, Java isn't smart enough to know that's a String array, or an array of Objects. So you need to specifically tell Java that it's a String array by including the String[] part.
Edit: I will also note that you could use varargs instead of an array as the argument to your main() method:
public static void main(String... args){
And then you can call your main() method with a String literal instead of an array, just like this:
main("!2312");
Your whole program might look something like this:
public class Main{
static int i = 0;
public static void main(String... args){
if (++i == 1){
main("!2312");
}
}
}
That's slightly outside your question, but it might be useful for you to know.
The problem with literals like {"!2312"} is that they do not have type information. E.g., Java has no way of knowing if you mean a String[] with one value or an Object[] with one value. You need to explicitly specify it, either by initializing a variable:
String asda[]={"!2312"};
if(++i==1)
main(asda);
or by calling the new operator:
if(++i==1)
main(new String[]{"!2312"});
In the previous code when you passed asda to main through
main(asda);
asda was an array but {"!2312"} is not an array and the main method accepts string arrays as specified in the declaration
public static void main(String args[])
where args is an array. So you should pass an array to main.
Create an array then place that string literal in it and then pass it to main.
Is it possible to have the main method accept an argument other than a string array? For example, can we have a method like main(Animals[]args){/*code*/}? If not, then why?
No - the entry point is always the method with the header public static void main(String[] args) (i.e. the JVM invokes this particular method). You can certainly define a method
public static void main(Animals[] args) {...}
but it would not be executed directly upon running the program.
EDIT: The reason the main method specifically has a string-array argument is because this array will contain the command-line arguments when the program is run. Intuitively, these should be strings (and certainly not Animals, for example).
Because when you input from the command line you are entering strings, not a complex type.
So it makes sense for the argument to be an array of pointers (references) to strings, including or not (depending on the language) the count of the arguments. In Java this isn't needed as you can just use length.
Not sure why you'd want that?..
The spec says it can only handle array of Strings.
There is nothing stopping you from having a public static void main that takes a parameter type other than String. The problem is the that the JVM needs simple rules for identifying and calling the method. It has an array of strings, e.g. from the command line, available to pass to the program. How would the JVM go about turning it into an array of Animal, or some other type, before it has started running your program?
Here's an example of a main that takes a different parameter type, and of the program itself dealing with producing the Animal array from the array of strings that the JVM has. Of course, it would really be better to give the second main method a more meaningful name.
import java.util.Arrays;
public class Bad {
public static void main(String[] args) {
Animal[] animals = new Animal[args.length];
for (int i = 0; i < args.length; i++) {
animals[i] = new Animal(args[i]);
}
main(animals);
}
public static void main(Animal[] args) {
System.out.println(Arrays.asList(args));
}
}
class Animal {
String species;
public Animal(String species) {
this.species = species;
}
public String toString() {
return "Animal: " + species;
}
}
Why are "Hi1" and "Hi3" displayed twice by the following code?
static int a=1;
public static void main(String[] args) {
if (a==2) { System.out.println(args[0]); a = 3;}
if (a==1) { main(); }
System.out.println("Hi1");
System.out.println(new PlayingWithMain().main("Hi3"));
}
public static void main() {
a = 2;
String[] a = new String[10];
a[0] = "Hi2";
main(a);
}
String main(String s) {
return s;
}
I have just started preparing for the OCPJP exam.
The first lesson — or trick, depending on how you look at it — of this question is that only one main method is special, no matter how many main methods are present. The special one is the one that takes the form
public static void main( /* multiple arguments */ ) { ... }
In the past, the argument had to be String[] args, but for recent versions, var-args are also acceptable (e.g. String... args). JLS 12.1.4
Now that we know which method to start with, we see that the first line checks the value of a. We see that it's initialized to 1, so we can ignore the a==2 line. Then, on the next line, we jump to the no-argument main.
In the no-arg main, a gets set to 2. The next lesson is that method-local variables can hide class variables. A new a gets declared, and it takes precedence inside the method but only lives as long as the method does. It's an array of strings of size ten, but only the first one is set (to "Hi2"). There's one more lesson in this method: this code is written to make you think the string-arg main gets called next, but it doesn't, because we haven't created an object and it's not static. Instead, we go back to main(String[] args).
This time, a is 2 — remember, we set it in the no-arg main, and a is static so the change sticks around — so we print the first argument, "Hi2." Next, we set a to 3, so the upcoming a==1 test fails. In the following line, we print "Hi1" for the first time and create a new instance of PlayingWithMain, which I assume is the class that the whole code snippet lives in.
Since a is static, its value remains 3 even for the new object. However, since the object is calling main("Hi3"), we don't go to a static version of main; instead, we go to the string-arg main. That method just kicks the input right back to the caller, where it gets immediately printed out.
That does it for the string-array-arg main, so we go back to the method that called it, the no-arg main. It's also finished, so we go back again, to the version of main(String[] args) that the JVM called. Remember, we just completed the line
if (a==1) { main(); }
so we move on to printing "Hi1" again. Finally, we repeat the last line, which creates another new PlayingWithMain object and prints "Hi3" one last time.
main(String[]) calls main() which again calls main(String[]) if a==1, which is true at the beginning.
The a variable is used to make this recursion only happen once and not endlessly.
This is why the main(String[]) method is executed twice, and this is why the output written from that method appears twice.
class Test{
public static void main(String... s){
System.out.println("Hello");
}
}
class Test{
public static void main(String[] s){
System.out.println("Hello");
}
}
What is the difference between above two syntax of main() declaration?
Does Java has any special need to have variable length argument?
No difference (when you run the program from the command line, i.e. what the main method is used for). The first variant appeared after Java 5 introduced varargs.
In short, varargs allows you to pass a variable number of arguments to a method. For the method body the arguments are grouped into an array. Like Test.main("foo", "bar") instead of Test.main(new String[] {"foo", "bar"}). The compiler does the array creation for you behind the scene.
The only difference is if you call main directly from other Java code. The first form allows you to write:
Test.main("first", "second", "third");
whereas the second would require you to create an array explicitly:
Test.main(new String[] { "first", "second", "third" });
Personally I don't think I've ever seen the first form used - calling main from other code is pretty rare. There's nothing wrong with it though.
There is no difference.
In general, String... s allows to pass arguments with comma as separator, while the String[] s requires an array.
But in the implementation s is array in both cases. So ... is sintactic sugar in a sense.
Variable number of arguments main(String... s) was only introduced in Java 5.0.