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.
Related
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;
}
}
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.
I'm currently working on a school project in Eclipse (We have just started using this) and we are running into a small hickup: Because we used BlueJ before, we did not have any main method, we added one but ran into a problem.
We have to send an Int value in the parameter instead of a String[] with args, we tried
public static void main(Int[] args)
This results in the following error:
Error: Main method not found in class Tester, please define the main
method as: public static void main(String[] args)
I'm wondering what we should do/change to get this to work.
Have a look into Integer.parseInt("123"),
see http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29
I hope you'll figure out the rest :)
Java will look for public static void main(String[] args).
You will have to pass the integer value as a String and parse it.
Here is a link to the documentation for Integer.parseInt(String).
As others have said, you cannot change the signature of the main method. To obtain an integer from the String parameters use:
public static void main(String[] args) {
int first = Integer.parseInt(args[0]); // use whatever index you need
}
Just like the error says, the main method that will be invoked when you execute the class must have the signature public static void main(String[] args). You can't just give it different arguments.
If you pass numbers as arguments on the command line, they will be read in as strings by Java. If you want to convert them to a numeric type, you must do so explicitly in your code.
Try sending your integer in the String array.
new String[]{"1"}
Then fetch it:
Integer yourInteger = Integer.valueOf(args[0])
You need to pass your value as a String then parse it as an Integer.
Look this sample of code :
public static void main(String[] args) throws Exception {
int value = Integer.parseInt(args[0]);
System.out.println("My int value: " + value);
}
You need to protect the parseInt with try catch for error management, if parameter is not parsable.
Just pass in a string, and then use Integer.parseInt(string) to get the integer you need back.
write a main method like below
public static void main(String[] args){
}.
and use Integer.parseInt(str)
You must leave the main method as follows:
public static void main(String[] args){
//....
}
As you indicate the error. Now, in the main method can change the type of the arguments to integers.
public static void main(String[] args){
int arg0=Integer.parseInt(args[0]);
int arg1=Integer.parseInt(args[1]);
//... etc.
}
Regards!
This class will print out the integers you put in on the command line:
public class IntegersFromCommandLine
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++)
{
System.out.println(Integer.parseInt(args[i]));
}
}
}
If you give it the command line arguments 1324 21 458 9564 1 0 -789 40, it will give the following output:
1324
21
458
9564
1
0
-789
40
The signature of the main method cannot be changed. This is a constraint of the operating system.
Just parse the String into an integer via Integer.parseInt(...), then invoke the actual method!
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.